2016-10-18 54 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的工作正常。很高兴你在最后工作,但:)快乐的编码! –