简体   繁体   中英

How to deserialize a Json dictionary to a flat class with NewtonSoft Json.Net

i am getting 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 that string to a .Net-class by using NewtonSoft Json.Net which works pretty well as my classes right 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; }
}

I would however much more prefer a flattened version of my class, without a dictionary like this:

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

I have however no clue of how to achieve this because i don't know how to access the keys in a customconverter like this:

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

Just in case someone cares, a link to a page where actual samples of the Json strings i get can be found: Ninjablocks Rest API documentation with json samples

I don't know if there's a way to do that with JSON.NET. Maybe you're overthinking it. How about creating a separate DTO type for deserializing the JSON, then projecting the result into another type suited more to your domain. For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM