简体   繁体   中英

Deserializing a JSON file with different object types for each key value

I have a json object like this

{
  "UrbanSourceUnsealedRoad": 
  [
    {
      "Name": "Baseflow Total Nitrogen Standard Deviation (log mg/L)",
      "Min": "1",
      "Max": "2",
      "Default": "3",
      "AlwaysInReport": "FALSE",
      "Flag": "YES"
    },
    {
      "Name": "Stormflow Total Nitrogen Mean (log mg/L)",
      "Min": "4",
      "Max": "5",
      "Default": "6",
      "AlwaysInReport": "FALSE",
      "Flag": "YES"
    },
    ...
  ],
  "UrbanSourceSealedRoad": 
  [
    {
      "Name": "Baseflow Total Nitrogen Standard Deviation (log mg/L)",
      "Min": "1",
      "Max": "2",
      "Default": "3",
      "AlwaysInReport": "FALSE",
      "Flag": "YES"
    },
    {
      "Name": "Stormflow Total Nitrogen Mean (log mg/L)",
      "Min": "4",
      "Max": "5",
      "Default": "6",
      "AlwaysInReport": "FALSE",
      "Flag": "YES"
    },
    ...
  ],
  ...
}

I have deserialised this using JSON.net in C#

JsonConvert.DeserializeObject<Dictionary<string, List<ParameterInfo>>>(json)

This works fine, however now I would like to change the json so that it contains an extra field at the top of the file.

ie:

{
    "UrbanLandUse" : ["UrbanSourceMixed", "UrbanSourceSealedRoad", "UrbanSourceUnsealedRoad" ], 
    "UrbanSourceUnsealedRoad": 
    [
        { 
        ...

But now my json file is no longer a dictionary containing List<ParameterInfo>

The JSON Spec seems to indicate that it is indeed possible

But I'm not sure how to deserialize it with the JSON.net API

Can I do this?

Prepare a containing object which contains ParameterInfo and the new one you want. Something like this:

public class Container
{
    public Dictionary<string, List<ParameterInfo>> {get; set;}
    public string[] UrbanLandUse {get; set;}
}

Then deserialize into that object like this:

JsonConvert.DeserializeObject<Container>(json);

Let me know if this works.

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