1

I'm getting this json from an API.

string json = "{'serviceSession':{ '123123123':[{'apn':'abc'},{'apn':'bcd'},{'apn':'def'}]}}"; 

When I'm trying to deserialize it with

public class ServiceSession { public Dictionary<string, List<ServiceSessionType>> ServiceSessions { get; set; } } public class ServiceSessionType { public string Apn { get; set; } } 

and

var test = JsonConvert.DeserializeObject<ServiceSession> (json); 

I'm getting null.

What's wrong? any ideas?

Thank you in advance!!

5
  • 1
    The c# data structure does not match the json data structure. Either change the way the json is composed, or change the class structure in c#. Commented May 2, 2018 at 6:55
  • 1
    Your model doesn't match your JSON. 123123123 is an array of objects, not a dictionary. Even if it were a dictionary (which it most definately is not) it would still blow up because you would have duplicate keys. Commented May 2, 2018 at 6:56
  • 6
    ServiceSessions is not the same as serviceSession Commented May 2, 2018 at 6:56
  • @SamAxe 123123123 is the key in the dictionary :) Commented May 2, 2018 at 6:56
  • @zaitsman: oh man. totally misread that one didnt I :) Thanks. Commented May 2, 2018 at 6:58

1 Answer 1

4

There is a missmatch between the datastructure and the json string. You need to change:

public class ServiceSession { //ServiceSessions replaced by serviceSession public Dictionary<string, List<ServiceSessionType>> serviceSession { get; set; } } 

Another solution is to add a DataMember attribute which tells the deserializer the name.

[System.Runtime.Serialization.DataContract] public class ServiceSession { [System.Runtime.Serialization.DataMember(Name = "serviceSession")] public Dictionary<string, List<ServiceSessionType>> ServiceSessions { get; set; } } 

This makes sense if you can't change the class or the name is a keyword in C#.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.