- Home /
JSONUtility creates a null object of subclass even when no data
Hi,
The JsonUtility's FromJson behaves strangely for subclass parsing..
Example:
[Serializable]
public class Player {
public int id;
public string name;
public PlayerSkills skills;
public static new Player createFromJSON(string jsonstring) {
return JsonUtility.FromJson<Player>(jsonstring);
}
}
If the json data received from server is {"id":123, "name":"Rajat"}
and the data for skills is not given, the values of the field skills
is still an object of class PlayerSkills
instead of being null.. and the value for fields in skills
are default values, eg 0
for a int
field..
How to differentiate between server sending the data of skills as value zero and server not sending the data at all..
In your documentation at https://docs.unity3d.com/Manual/JSONSerialization.html its bit ambiguous, can you explain what will be the constructed value for subclass..
If the JSON data contains values that do not map to fields in MyClass then those values will simply be ignored, and if the JSON data is missing values for fields in MyClass, then those fields will be left at their constructed values in the returned object.
We are trying to port our app form android, and the behaviour there for json parsing will the that the field will have null value if there is no data sent for it..
Did you find an answer ? I have the same problem. I have server side code that I cannot change and i must handle this kind of not sent values from server.
Answer by xxxmatulisxxx · May 28, 2021 at 03:37 PM
Hi, you have never constructed PlayerSkills class :)
public PlayerSkills skills; change to: public PlayerSkills skills = new PlayerSkills();
This is the default construction of class, you can make your own construction function but in C# class named functions is default construction :) I hope it will help you :)
You post an answer to a question that is 5 years old? Also what you just said doesn't have anything to do with what was asked....
His problem was not that the skills field is null, but that it is not null. This however is the normal behaviour of Unity's serialization system. Sub classes are treated like structs, so they are always created by the deserializer. However since the json data does not contain any information for that class, the sub class will have its default values.
Specifically Unity's serialization system does not support "null" values except for UnityEngine.Object derived types. However those are not really supported by the JsonUtility class.
Please do not necro-post such ancient questions. The OP was last seen in 2017...
Your answer
Follow this Question
Related Questions
Paring json Array object 3 Answers
Parsing Facebook graph JSON 1 Answer
Deserialize nested Json data 1 Answer
Can't read float array into C# from JSON using Simple JSON 2 Answers
Looking for Code that will Read JSON files (C# code) 2 Answers