Search code examples
c#jsonunity-game-enginejson.netjson-deserialization

How can I deserialize my JSON for C# so that I can request a specific duplicate variable?


I have a JSON string that I would like to de-serialize for my Unity game using C#. The string looks like this: https://i.sstatic.net/cq5CF.png

A more basic JSON formatted version would be this, for help explaining.

{
 "Entries": [
    {
        "Logical": "Easy",
        "EncounterType": "Standard",
        "EnrageType": "None",
        "WaitForCameraTime": 30,
        "OfflineExpireTime": 60,
        "UI": {
            "UseShocker": true,
            "UseFlashlight": true
        },
    },
    {
        "Logical": "Medium",
        "EncounterType": "Standard",
        "EnrageType": "None",
        "WaitForCameraTime": 30,
        "OfflineExpireTime": 60,
        "UI": {
            "UseShocker": true,
            "UseFlashlight": true
        }
    },
    {
        "Logical": "Hard",
        "EncounterType": "Standard",
        "EnrageType": "None",
        "WaitForCameraTime": 30,
        "OfflineExpireTime": 60,
        "UI": {
            "UseShocker": true,
            "UseFlashlight": true
        },
    }
 ]
}

How can I deserialize this string for Unity (using Newtonsoft json.net or another method) so that I can request something based on the logical name? Example: the OfflineExpireTime for the Logical Medium.


Solution

  • If I got you correctly, I think the easiest way is to generate a class with something like this https://json2csharp.com/

    That will give you this:

    // Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
        public class Entry
        {
            public string Logical { get; set; }
            public string EncounterType { get; set; }
            public string EnrageType { get; set; }
            public int WaitForCameraTime { get; set; }
            public int OfflineExpireTime { get; set; }
            public UI UI { get; set; }
        }
    
        public class Root
        {
            public List<Entry> Entries { get; set; }
        }
    
        public class UI
        {
            public bool UseShocker { get; set; }
            public bool UseFlashlight { get; set; }
        }
    

    As the comment says you can then get it with:

    Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
    

    Edit after comment:

    You can than e.g. loop through the list of Entries like this:

    
    Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
    
    foreach (var entry in myDeserializedClass.Entries) 
    {
        if (entry.Logical == "Easy")
            Debug.Log(entry.OfflineExpireTime + ", " + entry.UI.UseShocker);    
    }