Deserialize json dictionary to c#

假如想象 提交于 2021-02-10 19:52:51

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/50128713/deserialize-json-dictionary-to-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!