【问题标题】:Building a class to deserialize json to when one properties can be of two different types构建一个类以将 json 反序列化为一个属性可以是两种不同类型的情况
【发布时间】:2018-04-04 19:00:37
【问题描述】:

我有一些 Json 想要解析为一个可以像这样通过的 c# 对象: { "SomeObject" : { "name" : "something", "birthMonth" : "may" } }

或者像这样:

{ "SomeObject" : { "name" : "something", "birthMonth" : 5 } }

有没有一种方法可以为我的 SomeObject 类建模,以便birthMonth 属性可以是字符串或整数?

【问题讨论】:

  • 它想成为一个字符串,让它成为一个字符串。

标签: c# json parsing json.net


【解决方案1】:

是的。您可以使用dynamic 关键字。

public class SomeObject {
    public string name {get;set;}
    public dynamic birthMonth {get;set;}
}

但更好的方法可能是使用一些 json(依赖于框架)技术将 may 值转换为 5。例如在 newtonsoft.json 中有一个变体是使用您自己的 JsonConverter 实现。

这是一个例子: How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-24
    • 2013-07-29
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多