【问题标题】:How to deserialize JSON to my custom Class如何将 JSON 反序列化为我的自定义类
【发布时间】:2014-11-23 12:20:02
【问题描述】:

我是 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;
 }

错误:

Message=指定的转换无效。

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; }
}

我正在寻找只改变方法(序列化和反序列化)的东西,不能改变我的所有模型(它是没有任何单元测试的遗留物)。

【问题讨论】:

  • 看起来好像是因为ModelTest 中的Id 是一个对象而不是一个int。你需要它成为一个对象吗?
  • 此外,您还需要一个 $id 字段,这不是您的 RootObject 字段名称所建议的有效的 C 锐利标识符。
  • 是的,它是一个对象,因为某些模型转换为(长?),在极少数情况下它是一个结构。

标签: c# json serialization json.net deserialization


【解决方案1】:

您需要做的就是更改 Id 属性的 set 方法。 (因为value是从json读取的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; }
    }

【讨论】:

  • 不能将 long 转换为 int,它会抛出异常,但如果我这样做: set { this._id = value != null ? Convert.ToInt32(value) : (int?)null;它有效,但我必须更改所有模型.. 这不好,有什么建议吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-23
  • 2023-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多