2016-10-18 173 views
0

我想使用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);

+0

你的代碼適合我Json.Net 7 – Nico

+0

所有反序列化對我來說都很好 - 只是逐字測試你的代碼。使用Newtonsoft.Json版本9.0.1 –

回答

0

我用Newtonsoft.Json 8.0.2.19309。 我不得不將JsonProperty屬性添加到Player類中的Address對象中。然後該對象得到反序列化就好了。

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; } 
} 
+0

那麼您使用的是什麼版本的Newtonsoft.Json? –

+0

Newtonsoft.Json 8.0.2.19309是這個項目使用的一個。 – neuzehie

+0

非常奇怪,如果沒有'[JsonProperty]'屬性,它會反序列化,當它和我的和heinzbeinz的工作正常。很高興你在最後工作,但:)快樂的編碼! –