2013-04-01 36 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

相关问题