Home > Software engineering >  c sharp, json deserialize square bracket with unknown key
c sharp, json deserialize square bracket with unknown key

Time:09-12

I have problem with deserialize json file with square brackets and unknown name keys. Maybe someone have some idea how to do it? I readed all similar question but nothing works.

json file

[
  {
    "item1": {
      "value1": "rhe5h45h",
      "price1": "3.34"
    }
  },
  {
    "ddddd: {
      "value1": "cef3f",
      "price1": "1.1",
    }
  },
  {
    "rrrrr678": {
      "value1": "dfdf",
      "price1": "2"
    }
  }
]

class

public class itemList
{
    [JsonProperty("value1")]
    public string value1 { get; set; }

    [JsonProperty("price1")]
    public double price1 { get; set; }
}

cs:

var obj = JsonConvert.DeserializeObject<Dictionary<string, itemList>>(jsonFile);

CodePudding user response:

I would probably do it this way (after correcting your JSON for the missing ":

Youe class would be:

public class Item
{
    [JsonProperty("value1")]
    public string Value1 { get; set; }

    [JsonProperty("price1")]
    public double Price1 { get; set; }
}

And to deserialise, you need a list of dictionaries:

var obj = JsonConvert.DeserializeObject<List<Dictionary<string, Item>>>(jsonFile);

CodePudding user response:

Use List

var obj = JsonConvert.DeserializeObject<List<Dictionary<string, itemList>>>(jsonFile);

CodePudding user response:

Your issue is that you are not Deserializing a Dictionary, this is an array (or list) of Key\Value pairs.

Your code could change to something like below to work.

var obj = JsonConvert.DeserializeObject<List<Dictionary<string, itemList>>>(jsonFile);

To deserialize a Dictionary the parser would expect a key vaule (unique key) pair such as the json below.

{
    "item1": {
        "value1": "rhe5h45h",
        "price1": "3.34"
    },
    "ddddd": {
        "value1": "cef3f",
        "price1": "1.1"
    },
    "rrrrr678": {
        "value1": "dfdf",
        "price1": "2"
    }
}

CodePudding user response:

I'm not sure if it's a typo, but the json code you uploaded is missing a quotation mark. The correct deserialization would be:

var obj = JsonConvert.DeserializeObject<List<Dictionary<string, itemList>>>(jsonFile);

Fixed json code:

[
  {
    "item1": {
      "value1": "rhe5h45h",
      "price1": "3.34"
    }
  },
  {
    "ddddd": {
      "value1": "cef3f",
      "price1": "1.1",
    }
  },
  {
    "rrrrr678": {
      "value1": "dfdf",
      "price1": "2"
    }
  }
]
  • Related