简体   繁体   English

JSON.NET 使用自定义规则反序列化 JSON 到 object

[英]JSON.NET deserialize JSON to object with customized rules

I am trying to deserialize some JSON for which the format has changed.我正在尝试反序列化一些格式已更改的 JSON。

Previously, the JSON format was like this:之前的JSON格式是这样的:

{
  "crs": [123],
  "plugins":{...},
  // other fields...
}

So, I defined my class as the following:因此,我将 class 定义如下:

public class MyClass
{
    [JsonProperty("crs")]
    public List<int> { get; set; }

    // other fields
}

And I deserialized it like this:我像这样反序列化它:

var serializer = new JsonSerializer();
var myclass = (MyClass) serializer.Deserialize(jsonInput, typeof(MyClass));

But now, the JSON format has changed.但是现在,JSON 格式发生了变化。 The crs field has been removed from the root and put into plugins as in the following: crs字段已从根目录中删除并放入plugins中,如下所示:

{
  "plugins": [
    {
      "crs": [
        {
          "number": 123,
          "url": "url/123"
        }
      ]
    }
  ]
}

I don't want any fields other than the number and I want to keep the original interface of MyClass , so that I don't need to modify other related methods which use it.我不想要除number以外的任何字段,我想保留MyClass的原始接口,这样我就不需要修改其他使用它的相关方法。

Which means that:意思就是:

Console.writeline(myclass.crs) 
=> [123]

And I want to keep the way that I am currently deserializing.我想保持我目前反序列化的方式。

var myclass = (MyClass) serializer.Deserialize(jsonInput, typeof(MyClass));

How do I make a modification to get this result?如何进行修改以获得此结果? I was thinking I could customize the get method of crs to retrieve the number from the plugins field, but I am new to .NET so I need some help.我在想我可以自定义crsget方法以从plugins字段中检索number ,但我是 .NET 的新手,所以我需要一些帮助。 Here is my idea:这是我的想法:

public class MyClass
{
    public List<int> crs { get {
       // customize the get method and only retrieve the crs number from plugin field
    }}
}

If you define a couple of extra classes to aid in deserialization, you can use the approach you suggested.如果您定义了几个额外的类来帮助反序列化,您可以使用您建议的方法。

Define a Plugin class and a Crs class like this:像这样定义一个Plugin class 和一个Crs class :

public class Plugin
{
    public List<Crs> crs { get; set; }
}

public class Crs
{
    public int number { get; set; }
    public string url { get; set; }  // you can omit this field if you don't need it
}

In your MyClass class, add a plugins property as a List<Plugin> , and then you can make your crs property pull the data from the plugins list to get the List<int> you want:在您的MyClass class 中,添加一个plugins属性作为List<Plugin> ,然后您可以让您的crs属性从plugins列表中提取数据以获取您想要的List<int>

public class MyClass
{
    public List<Plugin> plugins { get; set; }

    [JsonIgnore]
    public List<int> crs 
    { 
        get
        {
            return plugins.SelectMany(p => p.crs).Select(c => c.number).ToList();
        }
    }

    // other fields
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM