我正在使用JsonFx使用C# (通过Unity3D中的Mono )来序列化一些数据,但当我尝试反序列化数据时得到:"JsonTypeCoercionException:只有具有默认构造函数的对象才能反序列化。(Level[])“。
我尝试将默认构造函数添加到序列化的类中,但仍然收到错误。顺便说一下,我在一个类似的帖子中尝试了不同的建议:http://forum.unity3d.com/threads/117256-C-deserialize-JSON-array
下面是我的代码:
//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());
}
}
}这是它正在序列化的对象:
using UnityEngine;
using System.Collections;
using System;
public class Level {
public string Id;
public string LevelName;
public Level() {}
}有什么想法吗?我尝试过使用和不使用Level()构造函数。
发布于 2013-01-29 01:50:08
我相信您的JSON流实际上需要包含一个数组才能工作-它不能只是一个元素,因为您在反序列化中请求一个数组。
发布于 2018-09-20 09:44:03
我认为你需要Serializable属性。
[System.Serializable]
public class Level
{
public string Id;
public string LevelName;
}然后,您的json级别数组必须如下所示:
{
[
{
"Id" : "1",
"LevelName" : "first level"
},
{
"Id" : "2",
"LevelName" : "second level"
}
]
}https://stackoverflow.com/questions/14567666
复制相似问题