JSON parsing

Hello, i checked a lot of example of using JsonUtility but i can’t figure out what to do in my case.
I have this json:


{
"input": {
"title": {
"row": [
{
"game": [
"sfg",
"4"
]
},
{
"game": [
"4",
{
"output": "fg",
"player": {
"id": "ff",
"player2": {
"id":"cv"
}
}
}
]
}
]
}
}
}

What’s your question?

2 Likes

Nearly everyting in this json can be parsed using JsonUtility by just creating the correct nested classes. As a small pointer everything { } will become a class with [serializable], everything will become an array.

As far as I know though [“4”, {…}] is not supported in the default unity serialization as you can not mix types in an array (e.g. string and class in this case). So if you cannot affect the structure of the json (supplied by an external party) you will need to look at alternative json parsers like the popular Json.net.

And please edit the post with code tags and a json formatter to make the json readable.

1 Like

Hi thank you very much for your reply.
I am new to the unity and coding.
can you please explain how to use json.net.

Hi thank you for your response
i need to parse above json and use it in unity project. im not sure how to parse. can you please help me.

Json.net is available in the assetstore https://assetstore.unity.com/packages/tools/input-management/json-net-for-unity-11347 and has a lot of documentation/examples you can find on the internet.
With this you should be able to gradually built a parser for your json except the [4, {…}] part whch will likely require some advanced stuff I would need to read up on too.
For the first step don’t worry about it though and just get everything else to parse little by little. That should give us a good starting point for improvements and adding the [“4”, { }] stuff.

You need to read article about jsonutility.
https://docs.unity3d.com/ScriptReference/JsonUtility.html
https://docs.unity3d.com/ScriptReference/JsonUtility.FromJson.html

Create structures that match layout of your data, mark them as System.Serializable, and then read them using “JsonUtility.FromJson” method.

However, there’s a problematic part which cannot be read this way:

"game": [
                        "4",
                        {
                            "output": "fg",
                            "player": {
                                "id": "ff",
                                "player2": {
                                    "id":"cv"
                                }
                            }
                        }
                    ]

This requires variant elements in array, which is not something JsonUtility does.

So a good idea would be to alter the format, or if that is impossible, to read data using alternative library.