JSONparser, adding values and replace previous values?

Hi guy,

Would I have to create a new type of JSONparser? Or is there another (simple) way of adding values and replacing existing values to the JSON data array?

I have the following code:

function Start ()
{
	var data;
	
	data = JSONParse.JSONParse('{"request":{"foo":"0"}}');
	Debug.Log(data['request']['foo']); ~#1
		
	data['request']['foo'] = 1;
	Debug.Log(data['request']['foo']); ~#2
		
	
	data = JSONParse.JSONParse('{"request":{"foo":"2"}}');
	Debug.Log(data['request']['foo']); ~#3
	
	
	data = JSONParse.JSONParse('{"new_request":{"foo":"0"}}');
	Debug.Log(data['new_request']['foo']); ~#4
	
	Debug.Log(data['request']['foo']); ~#5
}

Debug.Log() results:

~#1: 0

~#2: 1

~#3: 2

~#4: 0

~#5: NullReferenceException: Object reference not set to an instance of an object

It appears the data var has been overwritten instead of adding the new_request. Which is logical of course but I want it to add. Like ‘+=’ can add a string to an existing string.

The reason I need this type of adding to work is because during my game I request data from my server with a www request. I want to be able to add the result of the request to a data array that has to be available during the whole game. But if the value already exists I’d like it to replace the previous value.

The JSONparser http://wiki.unity3d.com/index.php?title=JSONParse

You can use my SimpleJSON library which i recently uploaded to the wiki. It allows easy extending of an existing structure.

// ...
data = JSONParse.JSONParse('{"request":{"foo":"2"}}');
// Add "new_request" and "foo";
data["new_request"]["foo"] = "0";

Note: my framework currently only supports strings as data, but i have added casting properties. So you can do:

data["new_request"]["foo"].AsInt = 4;

var number = data["new_request"]["foo"].AsInt + 5;
//number will be an integer containing 9

ps: if i can find the time i will add true type support :wink:

you’re assigning a new value to “data” each time, so the old value gets garbage collected- that is, each time you have "data = " getting a result of JSONParse.JSONParse, it completely replaces the old object that used to be in “data”. it’s just like if you did x = 4; and then x = 5; x would be 5 at that point, not 4.

To achieve what you’re trying, it’s probably best to keep your data in some other structure: Use the JSONParser to parse your results from your server, and go through the data array using a foreach and copy the data into some persistent data structure that you keep around between requests. that way your persistent one won’t get replaced.