如何将JSON反序列化为我的自定义类

时间:2014-11-23 12:20:02

标签: c# json serialization json.net deserialization

我是JSON的新手(并且不确定它是否是正确的方法),我的问题是反序列化我的类,所有模型都实现了这个接口:

public interface IPersistent
{
  object Id { get; set; }
}

班级示例:

public class ModelTest : IPersistent
{
    private int? _id;
    public object Id
    {
        get { return this._id; }
        set { this._id = (int?)value; }
    }
    public string Name { get; set; }
 }

序列化方法:

 public void SerializeData<T>(T[] data)
 {
    var settings = new JsonSerializerSettings
                {
                    PreserveReferencesHandling = PreserveReferencesHandling.Objects,
                    DateFormatHandling = DateFormatHandling.IsoDateFormat
                };
    var result = JsonConvert.SerializeObject(data, Formatting.Indented, settings);
    //more things happen, but not affect serialized data.
 }

反序列化方法:

 public T[] DeserializeData<T>(string objCached)
 {
     var settings = new JsonSerializerSettings
                {
                    PreserveReferencesHandling = PreserveReferencesHandling.Objects,
                    DateFormatHandling = DateFormatHandling.IsoDateFormat
                }; //not sure if a need this settings, but...
     T[] result = JsonConvert.DeserializeObject<T[]>(objCached, settings);  //error here.              
     return result;
 }

错误:

  

消息=指定的演员表无效。

objCached数据:

[
  {
    "$id": "1",
    "Id": 1000,
    "Name": "Name 1"
  },
  {
    "$id": "2",
    "Id": 2000,
    "Name": "Name 2"
  },
  {
    "$id": "3",
    "Id": 3000,
    "Name": "Name 3"
  },
  {
    "$id": "4",
    "Id": 4000,
    "Name": "Name 4"
  }
]

我尝试使用以下方法验证JSON结果: http://json2csharp.com/

结果:

public class RootObject
{
    public string __invalid_name__$id { get; set; }
    public int Id { get; set; }
    public string Name { get; set; }
}

我正在寻找改变方法(Serialize和Deseriaize)的东西,不能改变我的所有模型(它没有任何单元测试的遗产)。

1 个答案:

答案 0 :(得分:0)

您需要做的就是更改Id属性的set方法。 (因为从json读取时value long ,因此无法将其转换为int?

public class ModelTest : IPersistent
    {
        private int? _id;
        public object Id
        {
            get { return this._id; }
            set { this._id = new Nullable<int>((int)(long)value); }
        }
        public string Name { get; set; }
    }