[英]How to deserialize a Json dictionary to a flat class with NewtonSoft Json.Net
我從一個我無法控制的服務中得到類似的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; }
}
我不知道如何實現這一點,因為我不知道如何訪問customconverter中的鍵,如下所示:
http://blog.maskalik.com/asp-net/json-net-implement-custom-serialization
萬一有人關心,可以找到一個鏈接到一個頁面,其中我可以找到Json字符串的實際樣本: Ninjablocks Rest API文檔與json樣本
我不知道是否有辦法用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
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.