JsonTypeCoercionException:只能对具有默认构造函数的对象进行反序列化

时间:2013-01-28 17:26:54

标签: c# mono unity3d

我正在使用C#(通过Unity3D中的Mono)使用JsonFx来序列化一些数据,但我得到:“JsonTypeCoercionException:当我尝试反序列化数据时,只能对具有默认构造函数的对象进行反序列化。(Level [])” 。

我已经尝试将一个默认构造函数添加到序列化类中,但我仍然得到错误。 Fwiw,我在类似的帖子中尝试了不同的建议: 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()构造函数。

2 个答案:

答案 0 :(得分:1)

我相信你的JSON流实际上需要包含一个数组才能工作 - 它不能只是一个单独的元素,因为你在反序列化中要求一个数组。

答案 1 :(得分:0)

我认为您需要Serializable属性。

[System.Serializable]
public class Level 
 {
     public string Id;
     public string LevelName;
 }

您的json级别数组必须如下所示:

{
  [
    { 
      "Id" : "1",
      "LevelName" : "first level"
    },
    { 
      "Id" : "2",
      "LevelName" : "second level"
    }
  ]
}
相关问题