1
{
  "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);
1
  • 1
    Your wrapper type expects an object with a single property, fruits. Your JSON doesn't define an object with a fruits property. Your JSON would have to be { "fruits": { "apple": {/*...*/}, "banana": {/*...*/} }. Commented Feb 17, 2022 at 12:00

2 Answers 2

3

you don't need any wrapper

var value=Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, item>>(jsonString);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

Why not just deserialize what they have, as Serge shows?
Because that doesn't match what's being asked in the question.
We read the question different, but that's okay.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.