2013-04-01 38 views
4

我是,我不控制服務得到類似的JSON:如何反序列化一個JSON字典到一個平面類NewtonSoft Json.Net

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

我想這個字符串反序列化到一個.net -class使用NewtonSoft Json.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 documentation with json samples

回答

3

我不知道是否有辦法用JSON.NET來做到這一點。也許你正在反思它。如何創建一個單獨的DTO類型來反序列化JSON,然後將結果投影到適合您的域的另一種類型。例如:

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 
    }); 
} 
+0

非常感謝你,甚至都沒有想過做這種方式。不過,如果任何人有想用JsonConverter做這件事的想法,我想聽聽它。 – Andreas

相關問題