Skip to main content
 首页 » 编程设计

c#之已解析的 JSON 对象的属性为空

2024年02月13日10shangdawei

我正在使用 Json.NET 反序列化以下 JSON:

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

我正在尝试将其解析为列表。

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

City类的定义:

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

结果是两个 City 对象的列表,但它们的所有属性都为空(id 为 0)。

谁能提醒我我做错了什么?提前致谢。

请您参考如下方法:

您的字段都被标记(默认)为私有(private)。 将它们更改为 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; } 
}