2

Language C#. Console Application.

I have a json document in following format:

{"Cars":{"Mercedes": 1,"BMW": 3,"Toyota": 0},"Bikes":{"Kawasaki": 5,"Pulsar": 4}}

I have following classes:

    public class Vehicles  
    {  
     public Cars cars {get; set;}
     public Bikes bikes {get; set;} 
    }

    public class Cars
    {
        Dictionary<string, int> carcount {get; set;}
    }

    public class Bikes
    {
        Dictionary<string, int> bikecount {get; set;}
    }

I have to deserialize the json into the class. I tried this

Vehicles jsondata = JsonConvert.DesrializeObject<Vehicles>(jsonstring);

I get the dictionaries in both bikes and cars as null. I know I am missing something very basic. But cannot figure out exactly what.
Also, the json string format cannot change. Class structure can change though.

Himanshu Tanwar
  • 378
  • 2
  • 18

2 Answers2

2

You need this:

public class Vehicles
{
    public Dictionary<string, int> Cars { get; set; }
    public Dictionary<string, int>  Bikes { get; set; }
}
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
2

You don't have a level called carcount or bikecount. Instead, you have the dictionaries immediately.

public class Vehicles  
{
    public Dictionary<string, int> Cars {get; set;}
    public Dictionary<string, int> Bikes {get; set;}
}

Note that property names are case sensitive, so be very careful when you mix casing.

(You could probably have done this a little easier by following the steps described in this answer. Unfortunately that doesn't take the dictionary into account. It will at least give you a starting point here the dictionary should be.)

Community
  • 1
  • 1
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • @John and yours, both are same answers and both are correct. I am choosing john's answer as accepted just because he answered early. – Himanshu Tanwar Apr 25 '17 at 14:08
  • It is hard to post any sooner if the other one just dumps some code. – Patrick Hofman Apr 25 '17 at 14:11
  • I did think the problem would be self-explanatory in comparison of the two. Plus I did upvote your answer since I felt it was better than mine. – ProgrammingLlama Apr 25 '17 at 14:19
  • I am not complaining @john. It is just a pity that users don't vote on the contents, but on who was first. Also, for a user unaware of binding principles it is hard to figure out why it is happening. They just use the code you provide until the next time they hit the same wall. – Patrick Hofman Apr 25 '17 at 14:20
  • The properties need to be `public` or it won't work. – Brian Rogers Apr 25 '17 at 14:59
  • @BrianRogers Good catch! Updated. – Patrick Hofman Apr 25 '17 at 15:00
  • The answer was pretty much self explanatory for me in case of @john's answer. So i upvoted his. Not always an explanation is needed to understand why something works. Especially in today's times. – Himanshu Tanwar Apr 26 '17 at 05:37