如何使用NewtonSoft Json.Net将Json字典反序列化为平面类

4

我从一个我无法控制的服务中获取到了类似的Json:

"SomeKey": 
{
    "Name": "Some name",
    "Type": "Some type"
},
"SomeOtherKey": 
{
    "Name": "Some other name",
    "Type": "Some type"
}

我正在尝试使用NewtonSoft Json.Net将该字符串反序列化为.Net类,目前我的类看起来像这样:

public class MyRootClass
{
  public Dictionary<String, MyChildClass> Devices { get; set; }
}

public class MyChildClass
{
  [JsonProperty("Name")]
  public String Name { get; set; }
  [JsonProperty("Type")]
  public String Type { get; set; }
}

然而,我更喜欢一个扁平化的类版本,不需要像这样的字典:

public class MyRootClass
{
  [JsonProperty("InsertMiracleCodeHere")]
  public String Key { get; set; }
  [JsonProperty("Name")]
  public String Name { get; set; }
  [JsonProperty("Type")]
  public String Type { get; set; }
}

然而,我不知道如何做到这一点,因为我不知道如何在这样的自定义转换器中访问键:

http://blog.maskalik.com/asp-net/json-net-implement-custom-serialization

如果有人在意,这里是一个链接,可以找到我获取的Json字符串的实际样例:Ninjablocks Rest API documentation with json samples

1个回答

3

我不知道是否有使用JSON.NET的方法来实现这一点。也许你正在想得太多了。那么,如何为反序列化JSON创建单独的DTO类型,然后将结果投影到更适合你领域的另一个类型中呢?例如:

public class MyRootDTO
{
  public Dictionary<String, MyChildDTO> Devices { get; set; }
}

public class MyChildDTO
{
  [JsonProperty("Name")]
  public String Name { get; set; }
  [JsonProperty("Type")]
  public String Type { get; set; }
}

public class MyRoot
{
  public String Key { get; set; }
  public String Name { get; set; }
  public String Type { get; set; }
}

然后您可以按如下方式进行映射:

public IEnumerable<MyRoot> MapMyRootDTO(MyRootDTO root)
{
    return root.Devices.Select(r => new MyRoot
    {
        Key = r.Key,
        Name = r.Value.Name
        Type = r.Value.Type
    });
}

非常感谢,我甚至没有想过用这种方法来做。不过,如果有人有使用JsonConverter的想法,我很愿意听听。 - Andreas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接