C# Unity JsonUtility, how can I turn this simple json into some kind of useful c# object?

Viewed 418

I'm very confused about the Unity JsonUtility, mainly due to lack of c# understanding. All their examples are with very non generic classes, but I need flexibility, and havent been able to find a good e2e example that worked for me.

I have this simple json data that I need to work with:

"{
  1: 987,
  2: 123,
  3: 001,
  4: 157,
}"

It's a key value object where both key and value are integers.

My problem is that the size of the object is unknow, the index could be ever increasing, and I do not understand how I can define a generic object (class?) in c# that JsonUtility can convert. Do I need to define a class, or can I do it inline? Do I need to define getters and setter, or are there some convenient wildcard dictionary like thingy that would be suitable?

I'm trying to achieve something like this:

 string jsonString = "{1:987,2:123,3:001,4:157}":
 var object = JsonUtility.FromJson<??????>(jsonString);
 Debug.Log(object[1]) // 987
 Debug.Log(object[99]) // undefined

And then I would like to be able to add new pair to the object and at last turn it into json again something like:

object[100] = 999;
const jsonString = JsonUtility.ToJson<??????>(object);
Debug.Log(jsonString) // "{1:987,2:123,3:001,4:157,100:999}":
1 Answers

KeyValuePairs or Dictionary is not supported by the built-in JsonUtility.


You can use Newtonsoft .Net JSON (there is a wrapper Package for Unity) where this would be a simple Dictionary<int, int>

var json = "{1:987,2:123,3:001,4:157}":
var values = JsonConvert.DeserializeObject<Dictionary<int, int>>(json);
Debug.Log(values [2]);

and

var values = new Dictionary<int, int>{ { 2, 123 }, {7, 345} };
var json = JsonConvert.SerializeObject(values);
Debug.Log(json);
Related