反序列化包含另一个对象的JSON对象

时间:2016-10-18 11:37:48

标签: c# json json.net deserialization

我正在尝试使用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时会抛出一个null引用异常:

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);

1 个答案:

答案 0 :(得分:0)

我使用的是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; }
}