- Home /
Unity json not deserialize correctly
With this class
public class ALLTrackerPropertiesServer
{
public List<TrackerPropertiesServer> objs;
}
[Serializable]
public class TrackerPropertiesServer
{
public int id = 0;
public int uses = -1;
public string contentDownloadUrl = "";
public string Contents = "";
public string MarkerlessContents = "";
public int MarkerlessDefault = 1;
}
I get this error
ArgumentException: JSON must represent an object type.
Using this code
ALLTrackerPropertiesServer unitymaledetto= JsonUtility.FromJson(json);
With this json
[{"id":1,"uses":"-1","contentDownloadUrl":"http:\/\/b-sito\/ac1.jpg","Contents":"1","MarkerlessContents":"1","MarkerlessDefault":"3"},{"id":2,"uses":"-1","contentDownloadUrl":"http:\/\/b-sito\/ac1.jpg","Contents":"1","MarkerlessContents":"1","MarkerlessDefault":"3"}]
Why??
Try cast it to your class type using:
ALLTrackerPropertiesServer unitymaledetto= (ALLTrackerPropertiesServer)JsonUtility.FromJson(json);
Or alternatively, I think there is a generic version of that function:
ALLTrackerPropertiesServer unitymaledetto= JsonUtility.FromJson<ALLTrackerPropertiesServer>(json);
The JSON you have here represents an ARRAY, not an object containing an array.
Answer by Bunny83 · Feb 22, 2021 at 05:17 PM
Unity's JsonUtility can only deserialize json that has an object as root element. As Hellium said your json has an array as root element. This is not supported by Unity's JsonUtility. Though you can wrap your json in an object.
JsonUtility.FromJson<ALLTrackerPropertiesServer>("\"objs\":{" + json + "}");
This should work as expected with your given classes. Of course your "ALLTrackerPropertiesServer" class also need to have the Serializable attribute which you may just have forgotten to copy here. Though if not make sure you add that attribute as well.
Your answer
Follow this Question
Related Questions
How to Parse the JSON to get an array of image URLs. 0 Answers
i am fetch the images using (j son)server but it take too much time?? 0 Answers
Save Game format that is change proof and secure 0 Answers
TextAsset connected for app but not for TestRunner 1 Answer
How to import a list or array of objects from a json file? 1 Answer