【问题标题】:JsonTypeCoercionException: Only objects with default constructors can be deserializeJsonTypeCoercionException:只能反序列化具有默认构造函数的对象
【发布时间】:2013-01-28 17:26:54
【问题描述】:

我正在使用 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() 构造函数。

【问题讨论】:

    标签: c# mono unity3d


    【解决方案1】:

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

    【讨论】:

    • 不完全是这样,但你让我走上了正确的道路……我的 JSON 很不稳定。我通过 jsonlint.com 运行它并进行了相应的调整。
    【解决方案2】:

    我认为您需要 Serializable 属性。

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

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

    {
      [
        { 
          "Id" : "1",
          "LevelName" : "first level"
        },
        { 
          "Id" : "2",
          "LevelName" : "second level"
        }
      ]
    }
    

    【讨论】:

      猜你喜欢
      • 2013-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多