The question is answered, right answer was accepted
JsonUtility returns {}
I have this JSON fetched from web service:
{"city":{"cityName":"*****","distance":0,"latitude":*****,"cityId":3,"longitude":*****}}
this works fine in web browsers but if I run my code in unity, unity just displays { }.
class Coordinate
{
public string cityName;
public string distance;
public string latitude;
public string cityId;
public string longitude;
}
NameValueCollection values = new NameValueCollection();
values.Add("latitude", latitude.ToString());
values.Add("longitude", longitude.ToString());
values.Add("radius_in_km", "0.5");
Debug.Log("Latitude: " + values.Get("latitude") + ", Longitude: " + values.Get("longitude") + ", radius_in_km: " + values.Get("radius_in_km"));
string url = "";
WWW www = new WWW(url);
Debug.Log("Requesting the following url: " + www.url);
yield return www;
Coordinate json = JsonUtility.FromJson<Coordinate>(www.text);
if(www.error == null)
{
Debug.Log(json.cityId);
Debug.Log("Loaded following JSON string " + JsonUtility.ToJson(www.text));
}
else
{
Debug.Log("ERROR: " + www.error);
}
The code just gives me { }. Am I missing something? I am fairly new to JSON and Unity
Answer by superpig · Jul 27, 2016 at 01:36 AM
As @UnrealSoftware says, your type definition doesn't quite match your JSON - you're trying to read a Coordinate, but your JSON actually describes a bigger object which contains a Coordinate as the "city" field.
So, you need to define a second class, like this:
[Serializable]
class CityInfo
{
public Coordinate city;
}
and use FromJson with that. (Note that you should also put the [Serializable] attribute on your Coordinate class).
Answer by UnrealSoftware · Jul 21, 2016 at 02:14 PM
I'm not familiar with Unity's JSON functions and I'm not sure if these are the actual problems but I noticed two things:
Your class is called "Coordinate" but in the JSON the same thing is called "city"
Some values in the JSON seem to be integers or floats (the ones without quotes around the values) but in your class all values are strings.
Uhmm.. I never used JSON before. So.. if I change Coordinates to City and change the values to appropriate data types will it amend the issue?
I only used other JSON libraries, not the one from Unity. For other libraries it's crucial to get the data types and names right. It shouldn't be hard to test this so I guess you should give it a try.