简体   繁体   中英

Deserializing a JSON string into an object in C# and Unity

I am receiving a JSON string from an API and I need to deserialize it into something I can use in C# and Unity. I am trying to use Unity's JSON Serialization but it doesn't seem to be working for me?

Here is an example of the JSON structure from the API:

{
    "results": [
        [
            "2016-09-01/20160901_200002_000.jpg",
            "2016-09-01/20160901_192851_000.jpg",
            "2016-09-01/20160901_193443_000.jpg",
            "2016-09-01/20160901_210130_000.jpg"
        ],
        [
            "2016-09-02/20160902_104409_000.jpg",
            "2016-09-01/20160901_165949_000.jpg"
        ],
        [
            "2016-09-02/20160902_104409_000.jpg",
            "2016-09-02/20160902_104721_000.jpg",
            "2016-09-02/20160902_093420_000.jpg",
        ],
        [
            "2016-09-02/20160902_082554_000.jpg"
        ]
    ]
}

This is my code trying to deserialize the JSON into a custom class using Unity's JsonUtility class:

[Serializable]
public class MyClass
{
    public List<List<string>> results;
}

MyClass test = JsonUtility.FromJson<MyClass>(jsonString);
Debug.Log(test.results); // this is just returning null 

Anyone any idea what I'm doing wrong?

EDIT: This answer seems to suggest it is because JsonUtility does not support arrays and provides a helper class but it isn't working for this issue.

Here is the method I use to decode JSONs:

  1. Manage your NuGets and add Json.NET.Web to your references
  2. Copy paste the following method
  3. Make sure you are getting the right object. It looks like you have one key (="results") and whats comming next is the value corresponding to your key. You can eighter decode "results" and first remove all your brackets "[]" and then split the string by char[','] or form your JSON (if possible) with a key for each value and decode those values.

I hope it helps

public Dictionary<string, string> Decode(string encodedJson, string[] keys)
    {
        var details = JObject.Parse(encodedJson);
        Dictionary<string, string> decodedjson = new Dictionary<string, string>();
        foreach (var key in keys)
        {
            decodedjson.Add(key, details[key].ToString());
        }

        return decodedjson;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM