1

I am using Json.NET to deserialize the following JSON:

[
    {
        "id": 1234,
        "name": "Example",
        "coords": "[12:34]",
        "relationship": "ownCity"
    },
    {
        "id": 53,
        "name": "Another example",
        "coords": "[98:76]",
        "relationship": "ownCity"
    }
]

I'm trying to parse it to a List.

List<City> cities = JsonConvert.DeserializeObject<List<City>>(json);

The definiton of the City class:

public class City
{
    int id { get; set; }
    string name { get; set; }
    string coords { get; set; }
    string relationship { get; set; }
}

The result is a list of two City objects, but all of their properties are null (id is 0).

Could anyone give me a heads up what I'm doing wrong? Thanks in advance.

4

2 回答 2

3

您的字段都被标记(默认)为私有。将它们更改为 public 或 protected ,它应该可以正常工作:

public class City
{
   public int id { get; set; }
   public string name { get; set; }
   public string coords { get; set; }
   public string relationship { get; set; }
}
于 2013-06-04T11:43:18.737 回答
1

它会为你工作

  • 您需要添加公共访问级别

默认情况下,类成员和结构成员(包括嵌套类和结构)的访问级别是私有的。

  • 或者您需要对类的 DataContractAttribute 和对要序列化的成员的 DataMemberAttribute 属性。由于没有 [DataMember],您无法序列化非公共属性或字段

[DataContract] 公共类城市 {

 [DataMember]
public int id { get; set; }

  [DataMember]
  public string name { get; set; }

  [DataMember]
  public string coords { get; set; }

  [DataMember]
  public string relationship { get; set; }
}
于 2013-06-04T11:50:20.753 回答