Home > Net >  Deserialization of a json string gives null value
Deserialization of a json string gives null value

Time:02-17

{
  "apple": {
    "A": "xyz",
    "B": "abc",
    "C": "jkl"
  },
  "banana": {
    "A": "lotus",
    "B": "oil",
    "C": "cat"
  }
}

This is my JSON and below is my model class where I want to map the JSON data.

 public class Wrapper
    {
        public Dictionary<string, item> fruits{ get; set; }
    }
public class item
    {
        public string A{get; set;}
        public string B{get; set;}
        public string C{get; set;}
    }

when I am using the following code to deserialize the Json string I am getting null as response.

 var value=Newtonsoft.Json.JsonConvert.DeserializeObject<Wrapper>(jsonString);

CodePudding user response:

you don't need any wrapper

var value=Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, item>>(jsonString);

CodePudding user response:

Try wrap in an element fruits:

{
  "fruits":
  {
    "apple": {
      "A": "xyz",
      "B": "abc",
      "C": "jkl"
    },
    "banana": {
      "A": "lotus",
      "B": "oil",
      "C": "cat"
    }
  } 
}

To validate that your input is correct - instantiate an instance of the wrapper class and serialise it - then you can compare that your input matches the structure.

  • Related