- Home /
Parsing "complex" json
Hi all, I have a json file which have several entries types, how should I parse it?
[
{
"Name":"John",
"Health":3,
"Type":"Warrior",
"ExtendedData":{
"Shield":1,
"Damage":4
}
},
{
"Name":"Klara",
"Health":4,
"Type":"Witch",
"ExtendedData":{
"Magic":5,
"Mana":4
}
}
]
basically the Extended Data may be different for each entry
thanks
Answer by Bunny83 · Mar 06, 2021 at 09:39 AM
Well, one part is the parsing which is kinda trivial with a generic parser. However if you want to represent this data with C# classes it would be tricky. My SimpleJSON parser can parse any valid json and provides easy access to the data. It does not map the data to your own custom classes but just provides the data in the same structure only using the internal node classes. This allows direct access of any data that may be stored in the JSON.
Of course how you treat the different "extended data" sub classes is up to you. If they are specific for each "Type", you can map the data manually to your own classes. In this case you need to manually create the actual classes depending on the "Type" field. Once that's done, you could define an interface / abstract class that handles the deserialization (and serialization) for each individual class. I've posted several examples over here.
Note that you only need the SimpleJSON.cs file for the general parsing. However there are extension files which just need to be copied into your project as well which extend the support for other types. There's one for common Unity types like Vectors, but also one for common .NET types. As I explained in the answer I've linked above, you can create your own extention for types in your project which simplifies the usage. So you could implement a conversion operator that can convert a JSONNode into your base class type / interface and have it create the proper class depending on the "Type" field. Then just call your Deserialize method and pass the JSONNode along so each class can initialize itself from the json data.
It would be pointless to go more into detail here as it highly depends on your class structure on the C# side.
Your answer
Follow this Question
Related Questions
Why is JsonUtility.ToJson turning all my floats into doubles? 2 Answers
(SOLVED) Serializing different JSON objects, contained in an array, in another JSON object. (C#) 2 Answers
JsonUtility and Arrays [Error - "JSON must represent an object type"] 2 Answers
How do I go about deserializing a json array? 3 Answers
What are the pros and cons of ScriptableObjects vs. JSON for data files? 2 Answers