How do i use the deserialized JSON data and what is the better option to deserialize it?

Hello everyone,

I’m a both Unity and C# newbie, so excuse me if my question is dumb.

I have a small project that i’m working on, that i picked up to learn both of the aformentioned technologies. A part of this project is retrieving all the constant values from my JSON file and using them in my game. My JSON file is fairly simple, having a following structure:

{
    "heroes" : [
        {
            "heroNumber": 1,
            "heroName": "Alex",
        },
        {
            "heroNumber": 2,
            "heroName": "Bob",
        },
        {
            "heroNumber": 3,
            "heroName": "Chris",
        },
    ]
}

I do not intend to make the JSON file any more complex, other than, maybe, adding some more entries.

Now the code that reads the JSON file. I have two solutions for that, one being a more “complex” one and a “simpler” one.

I found the more complex one on stackexchange and it seems to work. However, i had to use a Json.NET for Unity package from jilleJr to make it work properly:

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using Newtonsoft.Json;

[System.Serializable]
public class HeroList : MonoBehaviour
{
    void Start()
    {
        Deserializer.DeserializingRootItem();
    }

[System.Serializable]

public partial class Deserializer
{
    public static void DeserializingRootItem()
    {
        string jsonPath;
        jsonPath = File.ReadAllText(Application.dataPath + "/list_of_heroes.json");
        RootItem deserializedHero = JsonConvert.DeserializeObject<RootItem>(jsonPath);

    }
  
}

[System.Serializable]
public class DeserializedHeroList
{
    public List<RootItem> deserializedHeroList = new List<RootItem>();
  
}

[System.Serializable]
public partial class RootItem
{
    [JsonProperty("heroes")]
    public List<Hero> heroes { get; set; }
}

[System.Serializable]
    public partial class Hero
    {
        [JsonProperty("heroNumber")]
        public int heroNumber { get; set; }
        [JsonProperty("heroName")]
        public string heroName { get; set; }

    }
}

For example: using the solution above, i’m able to deserialize the JSON and Debug.Log a value of my choosing (in this case of the second entry) by putting Debug.Log(deserializedHero.heroes[1].heroName) into the DeserializingRootItem(). However, i cannot understand how to use the deserialized data outside of that method.

I found another solution on Youtube

. I’ve tried it out as well

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class JSONdeserializer : MonoBehaviour
{
    public TextAsset textJSON;
  
    [System.Serializable]

    public class Hero
    {
        public int heroNumber;
        public string heroName;
    }

    [System.Serializable]
    public class HeroList
    {
           public Hero[] heroes;
    }

    public HeroList myHeroList = new HeroList();

    // Start is called before the first frame update
    void Start()
    {
        myHeroList = JsonUtility.FromJson<HeroList>(textJSON.text);
    }

    // Update is called once per frame
    void Update()
    {
      
    }
}

Now, the solution above lists the heroes in the inspector windows on project’s launch. However, i cannot understand how i use the data listed.

So eventually, i have several questions:

  • Which one of the two solutions would fit my simple JSON file deserialization needs better?
  • In the case of the first solution, how do i use the deserialized data outside of the DeserializingRootItem()?
  • In the case of the second solution, how do i use the deserialized data at all?

Thank you in advance for your answers.

In your final code sample, it seems like you have everything in place for loading your hero list into a field in your script. What part are you struggling with after that? Your myHeroList field has all your data, do with it what you want.

2 Likes

I realize you may have hand-monkey edited the JSON when posting it here, but beware the JSON you quoted at the top of your post is NOT VALID. It has at least four (4) illegal commas where none are permitted.

You can validate JSON at jsonlint.com.

Some JSON readers will happily guzzle down invalid JSON.

Some JSON readers will complain bitterly and loudly.

Some JSON readers will silently fail to hydrate all or part(s) of your invalid object, with no indication why.

Always lint your data, especially if you hand-edit it.

4 Likes

Yes, based on the pure JSON specification it’s not valid since JSON is just a subset of javascript. In pure js you are allowed to have trailing commas in objects or arrays. Though pure JSON does not allow such commas. The syntax of JSON can be best learned at json.org. A json file / fragment consists of a single “value”. So just follow the lines until you reach the end. As you can see, following a comma either inside an object or inside an array there has to be a next value

Now, assuming the json itself is fixed, back to topic. JSON is just an object notation format. So it describes objects in a string / text format. So after loading / parsing a json file you have the described objects as actual C# object in memory. So you can simply access any data you want from those objects like any other C# object. As @PraetorBlue said it’s up to you what you want to do with that data.

Just some quick notes on your code. In your first example, why do you have some of the classes be declared as partial classes? You should be careful with partial classes. They can easily lead to bad design choices and makes the code harder to read. You also seem to stick the Serializable attribute to literally every class, even those which are not serialized or do not contain any data that could be serialized (like the Deserializer class which is an empty class).

Your “DeserializedHeroList” class is not used at all so it’s just noise in your example which just blows up the code for no reason. We could say the same about the Deserializer class. If you strip them out the first solution is almost identical to the second, just using the Json.Net library instead. In your second example you create a new HeroList instance in this line:

public HeroList myHeroList = new HeroList();

However the deserializer does already create an HeroList instance based on the json and you actually replace it in this line

myHeroList = JsonUtility.FromJson<HeroList>(textJSON.text);

In both cases you will have that “heroes” list which you can read as usual. For example iterate through all elements of the array. In the first case you can do

foreach(Hero hero in deserializedHero.heroes)
{
    Debug.Log("Hero name: " + hero.heroName + " with number: " + hero.heroNumber);
}

This code would belong to line 24 after you deserialized your “deserializedHero” object.

In the second case it’s essentially the same but you would use “myHeroList” instead of “deserializedHero” since you named it that way.

1 Like

Wow! First of all, thank you all again for your replies, i didn’t expect them to come up so quickly.

Thank you for your answer PraetorBlue. The part i had trouble with is understanding exactly how to interact with that code. For whatever reason, after i tried the “simpler” solution and saw it pop up in the Inspector, i treated it as something that you cannot interact with in the same way i tried to interact with the “complex” one.

Thank you for your answer Kurt. Yes indeed, i edited the list to make it smaller because having 20 entries for no reason would be silly.
Thank you very much for the provided link and info about those picky JSON readers :slight_smile: I’ve checked the JSON that i’ve posted and it’s indeed bad. I checked the big one with the validator and it’s fine. I’ll be sure to use that resource in the future and hope to make a habit of linting the data.

Thank you for your answer Bunny83. I found this snippet as a part of a tutorial somewhere and i wouldn’t be able to answer you why exactly it’s there. However i’ve tried it and it seems to work just fine.
Could you provide some more explanation on why partial classes may lead to bad design choices? I’m new to it all and would be glad to get some extra info on good and bad practices.

Now the Serializable attribute was sticked because for whatever reason it wouldn’t work without it at the time. I removed the ones i’ve put before the HeroList class and Deserializer and it works just fine. Maybe i was trying another solution i’ve found somewhere and forgot to remove it.

So those two lines are unnecessary, right?

Thank you very much for your response. Funnily enough, i’ve found the answer to my second question almost right after i’ve made this post (how do i use the data outside of that specific method) which was to simply pass a reference type by reference. Basically i should’ve read the Microsoft C# guides a bit more careful instead of jumping up to making a post.

1 Like