问题
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