C#反序列化GeoJSON文件后Root及Properties对象为空的问题
解决C#中GeoJSON反序列化后对象为空的问题
问题背景
有一份GeoJSON文件片段如下:
{"type":"FeatureCollection", "features": [ {"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[45.882982627281955,35.98144306876872],[45.8830448154499,35.98142063110326],[45.883106013386524,35.98143674855534],[45.883177395327635,35.981590195979166],[45.88306057502328,35.98161790966196],[45.882982627281955,35.98144306876872]]]},"properties":{"Code":1,"Landuse":"fde","Longitude":45.8830793043,"latitude":35.9815185013}}, {"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[45.88321822952168,35.98143433703011],[45.88329577844585,35.981578778123584],[45.883184747057655,35.98160599975271],[45.883177395327635,35.981590195979166],[45.88313701140243,35.981503383976175],[45.883107851319025,35.981440699498734],[45.88321822952168,35.98143433703011]]]},"properties":{"Code":2,"Landuse":"fde","Longitude":45.8832014571,"latitude":35.9815182472}} ]}
尝试用C#读取并编辑该文件时,因ViewModel结构错误,导致反序列化后Root对象及properties均为空。
错误原因
原ViewModel结构与GeoJSON的层级完全不匹配:
- GeoJSON根节点是
FeatureCollection,包含features数组,每个元素是Feature对象 - 每个
Feature包含单个geometry和单个properties对象,而非List<Properties> - 原
Root类直接包含geometry和List<Properties>,没有对应features数组,导致反序列化无法匹配数据
修正方案
重新定义与GeoJSON结构完全对应的ViewModel:
public class Geometry { public string type { get; set; } public List<List<List<double>>> coordinates { get; set; } } public class Properties { public int Code { get; set; } public string Landuse { get; set; } public double Longitude { get; set; } public double latitude { get; set; } } public class Feature { public string type { get; set; } public Geometry geometry { get; set; } public Properties properties { get; set; } } public class Root { public string type { get; set; } public List<Feature> features { get; set; } }
修改后的操作代码
调整反序列化和编辑逻辑,遍历features数组找到目标Feature并修改其properties:
string json = File.ReadAllText(myPath); var deserialize = JsonConvert.DeserializeObject<Root>(json); foreach (var feature in deserialize.features) { if (feature.properties.Code == 2) { feature.properties.Landuse = "ppp"; // 替换为你的目标值 } } string output = Newtonsoft.Json.JsonConvert.SerializeObject(deserialize); File.WriteAllText(myPath, output);
额外注意事项
- 确保C#属性名与GeoJSON中的键完全一致(包括大小写,比如GeoJSON中的
latitude是小写,C#属性也要对应) - 如果需要更灵活的大小写匹配,可以给C#属性添加
[JsonProperty("键名")]特性,示例:[JsonProperty("latitude")] public double Latitude { get; set; }
内容的提问来源于stack exchange,提问作者mohammad
相关产品推荐
相关产品推荐

