我想使用Newtonsoft.Json庫反序列化這個JSON字符串。但是返回的反序列化對象allways返回null。我認爲它與播放器對象內的地址對象有關。反序列化包含另一個對象的JSON對象
這是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":[
"[email protected]",
"[email protected]"
],
"phone":[
""
]
},
"requestReference":2000,
"requestStatus":"Request OK",
"requestDetails":null
}
這些都是RootObject,播放器和地址類。它是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);
你的代碼適合我Json.Net 7 – Nico
所有反序列化對我來說都很好 - 只是逐字測試你的代碼。使用Newtonsoft.Json版本9.0.1 –