I have been fighting this one for a bit now, can't get the type casting right. I can deserialize a single JSON line but when I try to do an array, I'm running into problems. I have tried both the JSONFX code from here: https://bitbucket.org/darktable/jsonfx-for-unity3d/downloads as well as the MiniJSON script from here: https://raw.github.com/gist/1411710/MiniJSON.cs Here's my test code Code (csharp): using System; using System.Text; using System.Reflection; using System.Collections; using System.Collections.Generic; using JsonFX.Json; public class Person { public string Name { get; set; } public int Age { get; set; } public Person ( string name, int age) { Name = name; Age = age; } } public class test : MonoBehaviour { void Start() { Person person1 = new Person("Fred",5); Person person2 = new Person("Molly",13); object[] t = new object[2]; t[0] = person1; t[1] = person2; string json = JsonWriter.Serialize(t); // gives me the right string - [{"Name":"Fred","Age":5},{"Name":"Molly","Age":13}] List<Person> jsonObject = JsonReader.Deserialize<List<Person>>(json); //fails - Only objects with default constructors can be deserialized } } I'm missing something simple here - what is it? Thanks
You should try to deserialize an array instead of a list... Something like this.. Code (csharp): Person[] jsonObject = JsonReader.Deserialize<Person[]>(json);
Person[] did not work but object[] did. This gives me a dictionary that I can parse which is great. One more question - is there a way to cast the result back to Person? would be nice to have it back as the original but this at least gets me moving forward again Thanks
Not familiar with this JsonFX you are using, but the .Net equivalent would just work for Person[] as long as the original was also a Person[] Try changing object[] t = new object[2]; to Person[] t = new Person[2];
Found the problem. If I remove the setter from the Person class then it works just fine. Code (csharp): using System; using System.Text; using System.Reflection; using System.Collections; using System.Collections.Generic; using JsonFX.Json; public class Person { public string Name; public int Age; } public class test : MonoBehaviour { void Start() { string json = "[{\"Name\":\"Fred\",\"Age\":5},{\"Name\":\"Molly\",\"Age\":13}]"; Person[] jsonObject = JsonReader.Deserialize<Person[]>(json); foreach(var row in jsonObject) Debug.Log(row.Name); } } results in Fred Molly Thanks for the help
For future Googlers, the problem could also be fixed by adding a constructor with no parameters Code (csharp): public class Person { public string Name { get; set; } public int Age { get; set; } public Person() { // this is the default constructor that JSONFX wanted. } public Person ( string name, int age) { Name = name; Age = age; } }