0

I am receiving jsonstrings through a www call which looks like this:

{"Items":[{"Id":xxxxxx,"FirstName":"Carlo","LastName":"Carlosson","RatingAverage":0.0,"Subjects":[{"ID":xxxxxx,"SubjectTitle":"English","LevelTitle":"Some level here"}]},{"Id":xxxxxx,"FirstName":"Dennis","LastName":"Dennisson","RatingAverage":4.3,"Subjects":[{"ID":xxxxxx,"SubjectTitle":"Math","LevelTitle":"High"},{"ID":xxxxxx,"SubjectTitle":"English","LevelTitle":"High}]}]}

I then handle them like with this little class:

public static class JsonHelper
{
    public static T[] FromJson<T>(string json)
    {
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
        return wrapper.Items;
    }

    public static string ToJson<T>(T[] array)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper);
    }

    public static string ToJson<T>(T[] array, bool prettyPrint)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper, prettyPrint);
    }

    [System.Serializable]
    private class Wrapper<T>
    {
        public T[] Items;
    }
} 

I use the class like this:

Student[] students = JsonHelper.FromJson<Student>(jsonString);

I have these 2 models:

public class Student
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public double RatingAverage { get; set; }
    public List<Subjects> subjects { get; set; }
}

public class Subjects
{
    public int ID { get; set; }
    public string SubjectTitle { get; set; }
    public string LevelTitle { get; set; }
}

Now, the JsonHelper does some of the work. The student output is OK, but it does not seem to handle the nested array/list (Subjects) in the Student model.

How do i get this to work. Hope someone can help me with this and thanks in advance :-)

Mansa
  • 2,277
  • 10
  • 37
  • 67
  • This will helps you https://stackoverflow.com/questions/17481569/how-to-get-json-array-in-c-sharp – Hamza Haider Nov 21 '18 at 09:17
  • The json in your question is not even [valid](http://json2csharp.com/). Once you fix that, read the TROUBLESHOOTING section from the accepted answer in the duplicate and you'll see many other issues in the objects you're trying to de-serialize the json to. – Programmer Nov 21 '18 at 09:23

0 Answers0