【问题标题】:How to parse not fully corresponding json如何解析不完全对应的json
【发布时间】:2018-11-13 10:54:55
【问题描述】:

我正在使用第三方 API,因此无法更改响应结构。 作为回应,我得到了这样的结果:

{
    "Code": "SomeCode",
    "Name": "Some Name",
    "IsActive": true,
    "Prop13": {
        "LongId": "12",
        "ShortId": "45"
    },
    "Prop26": {
        "LongId": "12",
        "ShortId": "45"
    },
    "Prop756": {
        "LongId": "12",
        "ShortId": "45"
    }
}

我需要将其解析为下一个类:

public class Class1
{
    public string Code { get; set; }

    public string Name { get; set; }

    public bool IsActive { get; set; }

    public Dictionary<string, PropertiesClass> Properties { get; set; }
}

public class PropertiesClass
{
    public int LongId { get; set; }

    public int ShortId { get; set; }
}

属性“Prop13”、“Prop26”等是动态响应的,它们都不可能存在,或者完全是其他名称。因此,我必须只将 Code、Name 和 IsActive(始终存在)存储到类属性中,所有其他都应该存储到 Dictionary 中。并且属性的名称应该作为键存储在字典中。

我在 https://www.newtonsoft.com/json/help/html/Introduction.htm 中找不到任何可以帮助我的东西

【问题讨论】:

标签: c# json json.net


【解决方案1】:

我能想到一种方法。

您的Class1 需要稍作修改:

public class Class1
{
    public string Code { get; set; }

    public string Name { get; set; }

    public bool IsActive { get; set; }

    [JsonExtensionData]
    public Dictionary<string, JToken> _JTokenProperty { get; set; }

    public Dictionary<string, PropertiesClass> Properties1 { get; set; } = new Dictionary<string, PropertiesClass>();
}

然后在你解析对象的地方,你想像这样削减它:

var obj = JsonConvert.DeserializeObject<Class1>("{\"Code\":\"SomeCode\",\"Name\":\"Some Name\",\"IsActive\":true,\"Prop13\":{\"LongId\":\"12\",\"ShortId\":\"45\"},\"Prop26\":{\"LongId\":\"12\",\"ShortId\":\"45\"},\"Prop756\":{\"LongId\":\"12\",\"ShortId\":\"45\"}}");

foreach(KeyValuePair<string, JToken> token in obj._JTokenProperty)
{
    obj.Properties1.Add(token.Key, token.Value.ToObject<PropertiesClass>());
}

这将生成所需的输出。


编辑:感谢@Nkosi 提供的链接和建议,以使其保持独立。 您可以将以下内容添加到Class1

[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{

    foreach (KeyValuePair<string, JToken> token in _JTokenProperty)
    {
        Properties1.Add(token.Key, token.Value.ToObject<PropertiesClass>());
    }
}

你的反序列化就变成了:

var obj = JsonConvert.DeserializeObject<Class1>("{\"Code\":\"SomeCode\",\"Name\":\"Some Name\",\"IsActive\":true,\"Prop13\":{\"LongId\":\"12\",\"ShortId\":\"45\"},\"Prop26\":{\"LongId\":\"12\",\"ShortId\":\"45\"},\"Prop756\":{\"LongId\":\"12\",\"ShortId\":\"45\"}}");

【讨论】:

猜你喜欢
  • 2021-11-23
  • 2013-07-09
  • 2019-05-05
  • 2018-10-18
  • 2016-11-28
  • 2019-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多