How to deserialize a Json dictionary for a flat class using NewtonSoft Json.Net

I get a similar Json from a service that I do not control:

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

I am trying to deserialize this line in a .Net class using NewtonSoft Json.Net, which works very well since my classes now look like this:

 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; } } 

However, I would prefer a flatter version of my class without a dictionary:

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

However, I don’t have a clue on how to achieve this, because I don’t know how to access the keys in a custom converter in the following way:

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

Just in case anyone cares, a link to a page where you can find actual Json string samples: Ninjablocks Restore API documentation with json samples

+4
source share
1 answer

I don't know if there is a way to do this using JSON.NET. Maybe you overdid it. How to create a separate DTO type for JSON deserialization, and then project the result to another type, more suitable for your domain. For instance:

 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; } } 

Then you can display it as follows:

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

All Articles