Parsing a simple json object is always returning null properties,Parsing Always return empty object
I'm trying to deserialize a simple Json object using JsonUtility.FromJson. The thing I'm doing is very simple, but why I'm always having an object with null x, y and z.
var location = JsonUtility.FromJson<Location>("{\"x\":\"2060.0\",\"y\":\"-6140.0\",\"z\":\"-60.0\"}");
And here's my class Location
[Serializable]
public class Location
{
public string X { get; set; }
public string Y { get; set; }
public string Z { get; set; }
}
Any help??
Answer by Bunny83 · Apr 20, 2019 at 04:30 AM
Because you named the fields "x", "y" and "z" in your json but named them "X", "Y" and "Z" inside your class. Furthermore you used properties and not fields. Unity's serializer does not serialize properties, only fields. Unity's JsonUtility has the same restrictions as the normal serialization system (even more).
So assuming your json is what you want to use, your class should look like this:
[Serializable]
public class Location
{
public string x;
public string y;
public string z;
}
Thanks so much! Everything kept returning null
for my json text too, I even created a really simple example but still the same thing happened. You're correct, do NOT use getter/setter! Once I'd removed them everything started to work perfectly!