JSON utility with more complex JSON files

So they JSON Utility in Unity is ok… but I am very confused on how to access things from the JSON string that are children of other objects.

I realize that my wording is probably confusing and not very clear here, so here is an example of the JSON that I am working with.

============ JSON FILE =================
{
“took” : 4,
“timed_out” : false,
“_shards” : {
“total” : 5,
“successful” : 5,
“failed” : 0
},
“hits” : {
“total” : 32496,
“max_score” : 1.0,
“hits” : [
{
“_index” : “blah-blah”,
“_type” : “helpme”,


===========No more JSON file =================

I need to get at the data that inside of “hits”, and I’m not sure on how I can do that with the JSON utility, and how I need to structure my JSON object classes in C#.

Do I need an external JSON library for this? Any help would be appreciated.

The Unity jsonutility deserializes to a defined type in your program. So you’ll need to define a class (or set of classes if the objects nest) that mirror the shape of the json.

something like this:

public class Data
{
    public int took;
    public bool timed_out;
    public ShardsData _shards;
    public HitsData hits;
}

public class ShardsData
{
    public int total;
    public int successful;
    public int failed;
}

public class HitsData
{
    public int total;
    public float max_score;
    public HitsAuxData[] hits;
}

public class HitsAuxData
{
    public string _index;
    public string _type;
}

If you don’t want to have to do that… you can use a 3rd party library instead that allows traversing json generically.

Like json.net.

2 Likes

Ok so then what would the actual call to JSONUtility look like?

            Data dataObject = JsonUtility.FromJson<Data>(JSON_String);

Would I have to do that for every class? How many times would I have to call it? I am new to using JSON with Unity :slight_smile:

I usually use the site json2csharp to convert a json into classes. It provides properties, but I believe unity’s json uses fields instead and must be serialized. You normally deserialize your json string into a class and then you can access your data through the variables like normal. I’m not sure if Unity’s json lets you access the fields through the string by parsing it.

Personally for my own use, I use json.net from the asset store. https://www.assetstore.unity3d.com/en/#!/content/11347
I prefer it and he has brought the price down on it, which is nice.

Edit: Looks like @lordofduct beat me to it. :slight_smile:

How about this.

Try running the code… and see what happens.

You know… get a hands on experience with the thing.

What bad can happen? You get an error? Ain’t the end of the world. From failure comes experience.

1 Like

All is well, I understand how this works now. Thank guys for the help! I really appreciate it! :slight_smile: