【问题标题】:Can a JSON object with 2 different data types for the same property be deserialized with the same deserialization call?可以使用相同的反序列化调用反序列化具有相同属性的 2 种不同数据类型的 JSON 对象吗?
【发布时间】:2016-11-05 11:40:45
【问题描述】:

假设我有以下 2 个 JSON 对象,它们根据传入的参数从同一个 AJAX 调用返回。

第一个返回 child 属性的字符串数组:

{
    parent: {
        child: [
            "item 1",
            "item 2",
            "item 3",
        ]
    }
}

第二个返回 child 属性的对象数组:

{
    parent: {
        child: [
            {
                "attribute1": "Attribute 1",
                "attribute2": "Attribute 2",
                "attribute3": "Attribute 3"
            },
            {
                "attribute1": "Attribute 1",
                "attribute2": "Attribute 2",
                "attribute3": "Attribute 3"
            },
            {
                "attribute1": "Attribute 1",
                "attribute2": "Attribute 2",
                "attribute3": "Attribute 3"
            },
        ]
    }
}

是否有可能以某种方式将其中任何一个反序列化为同一模型?也许 child 有 2 个不同的属性(例如 ChildStringChildObject em>) 根据类型相应填充?

我目前正在使用Jil 进行反序列化,但如果需要,我愿意向其他人开放。

谢谢!

【问题讨论】:

标签: c# .net model-view-controller deserialization


【解决方案1】:

您可以为 child 使用泛型类型,并根据您的 json 传递两种不同的类型:

class Parent<T>
{
    public T child { get; set; }
}

class child
{
     string attribute1 { get; set; }
     string attribute2 { get; set; }
     string attribute3 { get; set; }
}

var parentWithList = JsonConvert.DeserializeObject<Parent<List<string>>>(yourFirstJson);

var parentWithSingleChild = JsonConvert.DeserializeObject<Parent<child>(yourSecondJson);

【讨论】:

    猜你喜欢
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    相关资源
    最近更新 更多