I’m working with JsonFx using C# (via Mono in Unity3D) to serialize some data but I get: “JsonTypeCoercionException: Only objects with default constructors can be deserialized. (Level[])” when I try to deserialize the data.
I’ve tried adding a default constructor to the serialized class but I still get the error. Fwiw, I tried the different suggestions in a similar thread:
http://forum.unity3d.com/threads/117256-C-deserialize-JSON-array
Here’s my code:
//C#
using System;
using UnityEngine;
using System.Collections;
using JsonFx.Json;
using System.IO;
public class LoadLevel : MonoBehaviour {
string _levelFile = "levels.json";
Level[] _levels;
void Start () {
if (!File.Exists (_levelFile)){
// write an example entry so we have somethng to read
StreamWriter sw = File.CreateText(_levelFile);
Level firstLevel = new Level();
firstLevel.LevelName = "First Level";
firstLevel.Id = Guid.NewGuid().ToString();
sw.Write(JsonFx.Json.JsonWriter.Serialize(firstLevel));
sw.Close();
}
// Load our levels
if(File.Exists(_levelFile)){
StreamReader sr = File.OpenText(_levelFile);
_levels = JsonReader.Deserialize<Level[]>(sr.ReadToEnd());
}
}
}
And here’s the object it’s serializing:
using UnityEngine;
using System.Collections;
using System;
public class Level {
public string Id;
public string LevelName;
public Level() {}
}
Any ideas? I’ve tried both with and without the Level() constructor.
I believe your JSON stream actually needs to contain an array for this to work – it can’t just be a single element since you’re asking for an array in Deserialize.