我正在尝试使用Newtonsoft反序列化这个JSON字符串。Json库。但是返回的反序列化对象总是返回null。我认为它与播放器对象中的地址对象有关。
JSON字符串
{
"player":{
"id":"ed704e61-f92b-4505-b087-8a47ca4d1eaf",
"firstName":"Jack",
"lastName":"Russel",
"nickname":"Barky",
"dateOfBirth":"1995-08-16T00:00:00",
"sex":"m",
"address":{
"street":"Elmstreet",
"number":"5",
"alphaNumber":"",
"poBox":"",
"postalCode":"90001",
"city":"Los Angeles",
"country":"United States"
},
"email":[
"barky@dog.com",
"barky@mydogpension.com"
],
"phone":[
"0123 45 67 89 10"
]
},
"requestReference":2000,
"requestStatus":"Request OK",
"requestDetails":null
}
这些是RootObject, Player和Address类。它是RootObject的Player对象,它为上面的JSON字符串返回一个空值。因此,在调用offcourse时,将抛出nullreference异常:
public class RootObject
{
public Player player { get; set; }
public int requestReference { get; set; }
public string requestStatus { get; set; }
public string requestDetails { get; set; }
}
public class Address
{
public string street { get; set; }
public string number { get; set; }
public string alphaNumber { get; set; }
public string poBox { get; set; }
public string postalCode { get; set; }
public string city { get; set; }
public string country { get; set; }
}
public class Player
{
public Guid id { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string nickname { get; set; }
public DateTime dateOfBirth { get; set; }
public string sex { get; set; }
public Address address { get; set; }
public List<string> email { get; set; }
public List<string> phone { get; set; }
}
这是用于反序列化的代码行:
RootObject playerRoot = JsonConvert.DeserializeObject<RootObject>(_the_json_string_shown_above);
我用的是Newtonsoft。Json 8.0.2.19309。我必须在Player类中的Address对象中添加一个JsonProperty属性。然后对象被很好地反序列化。
public class Player
{
public Guid id { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string nickname { get; set; }
public DateTime dateOfBirth { get; set; }
public string sex { get; set; }
[JsonProperty]
public Address address { get; set; }
public List<string> email { get; set; }
public List<string> phone { get; set; }
}