3

The Model

using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class GetPeopleResult
{
    public List<Person> people { get; set; }
    public GetPeopleResult()
    {
       this.people = new List<People>();
    }

    public static GetPeopleResult CreateFromJSON(string jsonString)
    {
        return JsonUtility.FromJson<GetPeopleResult>(jsonString);
    }

}
[System.Serializable]
public class Person
{
    public long id { get; set; }
    public string name { get; set; }
    public string email { get; set; }
    public string displayImageUrl { get; set; }

    public Person()
    {

    }
    public static Person CreateFromJSON(string jsonString)
    {
        return JsonUtility.FromJson<Person>(jsonString);
    }
}

The JSON

{
    "people":
    [{
        "id":1,"name":"John Smith",
        "email":"[email protected]",
        "displayImageUrl":"http://example.com/"
    }]
 }

The Code

string json = GetPeopleJson(); //This works
GetPeopleResult result = JsonUtility.FromJson<GetPeopleResult>(json);

After the call to FromJson, result is not null, but the people collection is always empty.

1 Answer 1

13

After the call to FromJson, result is not null, but the people collection is always empty.

That's because Unity does not support property getter and setter. Remove the { get; set; } from all the classes you want to serialize and that should fix your empty collection.

Also, this.people = new List<People>(); should be this.people = new List<Person>();

[System.Serializable]
public class GetPeopleResult
{
    public List<Person> people;
    public GetPeopleResult()
    {
       this.people = new List<People>();
    }

    public static GetPeopleResult CreateFromJSON(string jsonString)
    {
        return JsonUtility.FromJson<GetPeopleResult>(jsonString);
    }

}
[System.Serializable]
public class Person
{
    public long id;
    public string name;
    public string email;
    public string displayImageUrl;

    public Person()
    {

    }
    public static Person CreateFromJSON(string jsonString)
    {
        return JsonUtility.FromJson<Person>(jsonString);
    }
}
1
  • 2
    I didn't know about the { get; set; } "limitation" in Unity. That fixed the issue. As for the new List<Person>(); thing, that was just me misrenaming the variables to make the question more user friendly on StackOverlflow. Thanks
    – Dave
    Nov 4, 2016 at 19:20

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.