Gian-Marco Schmid
Gian-Marco Schmid

Reputation: 13

Deserialize json dictionary to c#

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!!

Upvotes: 1

Views: 152

Answers (1)

fubo
fubo

Reputation: 45947

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#.

Upvotes: 4

Related Questions