Deserialize JSON object array in C# using LitJson

Serge N. picture Serge N. · Feb 9, 2011 · Viewed 9.1k times · Source

I'm limited by Unity3d 3 new security measures to using LitJson for Web Player application, otherwise it won't compile.

Is there a simple way to serialize this output as an object (contents of userEcoGet.text):

{"building_id":"1","building_level":"0","workers":"0","building_health":"100"}{"building_id":"2","building_level":"0","workers":"0","building_health":"100"}...{"building_id":"32","building_level":"0","workers":"0","building_health":"100"}

This code only enters first object from JSON:

using UnityEngine;
using System.Collections;
using LitJson;
...
public EcoData localEcoData;
...
localEcoData = JsonMapper.ToObject<EcoData>(userEcoGet.text);
...
public class EcoData
{
    public string building_id;
    public string building_level;
    public string workers;
    public string building_health;
}

Turning localEcoData into array leads to missing constructor errors. And I just don't know how to nest constructor correctly in this situation, not even sure if it would help even.

At this point I'm resorting to using JsonReader and filling in object manually. Any help would be appreciated. Thank you.

Edit: That's just crazy, killed all day today just because of a crappy JSON formatting that I inflicted on myself...

This works perfectly now, localEcoData[1,2...32] is an object array with all elements accessible:

public EcoData[] localEcoData;
...
localEcoData = JsonMapper.ToObject<EcoData[]>(userEcoGet.text);

All I had to do is compose JSON correctly on PHP page which handles MySql and transfer back to Unity in orderly fashion. I was echoing directly without using an array for transfer. Now output looks like this and works great:

[{"building_id":"1","building_level":"0","workers":"0","building_health":"100"}{"building_id":"2","building_level":"0","workers":"0","building_health":"100"}...{"building_id":"32","building_level":"0","workers":"0","building_health":"100"}]

Thanks, man!

Answer

Shekhar_Pro picture Shekhar_Pro · Feb 9, 2011

I suspect the problem is with your JSON itself. its not in correct format. To parse it as JSON Array you will need to have it in format:

{
    result:[
                {"building_id":"1","building_level":"0","workers":"0","building_health":"100"},
                {"building_id":"2","building_level":"0","workers":"0","building_health":"100"},...
                {"building_id":"32","building_level":"0","workers":"0","building_health":"100"}
           ]
}

If you dont have control on the JSON then you may need to split the string and treat each string as a single JSON object and Convert each element in the array to you C# object type.