You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在ASP.NET Core C#中编辑GeoJSON文件:修改指定Code的Landuse值

问题:修改GeoJSON中指定Code的Feature的Landuse属性

需求为读取GeoJSON文件后,根据properties中的Code值修改对应的Landuse属性值。已完成GeoJSON到C#类的转换,以及文件读取和反序列化操作,现需实现查找指定Code的Feature、修改Landuse并更新原文件的逻辑。

已定义的C#类:

public class ConvertorJsonLayerDTO {
    public class Feature {
        public string type { get; set; }
        public Geometry geometry { get; set; }
        public Properties properties { get; set; }
    }

    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 Root {
        public string type { get; set; }
        public List<Feature> features { get; set; }
    }
}

已完成的读取反序列化代码:

var targetCode = 2;
var geoJsonPath = "你的文件路径";
var geojsonContent = File.ReadAllText(geoJsonPath);
var rootObject = JsonConvert.DeserializeObject<ConvertorJsonLayerDTO.Root>(geojsonContent);

解决方案

1. 查找目标Feature

使用LINQ查询rootObject.features列表,筛选出properties.Code匹配目标值的Feature:

var targetFeature = rootObject.features.FirstOrDefault(f => f.properties.Code == targetCode);

2. 修改Landuse属性

先判断是否找到目标Feature(避免空引用异常),再修改其Landuse值:

if (targetFeature != null)
{
    targetFeature.properties.Landuse = "新的土地用途值"; // 替换为你需要的具体值
}
else
{
    // 可选:处理未找到对应Code的场景,例如输出提示
    Console.WriteLine($"未找到Code为{targetCode}的Feature");
}

3. 序列化并写入原文件

将修改后的对象重新序列化为JSON,覆盖写入原文件:

var updatedGeoJson = JsonConvert.SerializeObject(rootObject, Formatting.Indented); // Formatting.Indented可选,用于生成格式化的可读JSON
File.WriteAllText(geoJsonPath, updatedGeoJson);

完整整合代码示例:

var targetCode = 2;
var geoJsonPath = "你的文件路径";

// 读取并反序列化GeoJSON
var geojsonContent = File.ReadAllText(geoJsonPath);
var rootObject = JsonConvert.DeserializeObject<ConvertorJsonLayerDTO.Root>(geojsonContent);

// 查找目标Feature并修改Landuse
var targetFeature = rootObject.features.FirstOrDefault(f => f.properties.Code == targetCode);
if (targetFeature != null)
{
    targetFeature.properties.Landuse = "新的土地用途";
}
else
{
    Console.WriteLine($"未找到Code={targetCode}的Feature");
}

// 保存修改后的内容
var updatedGeoJson = JsonConvert.SerializeObject(rootObject, Formatting.Indented);
File.WriteAllText(geoJsonPath, updatedGeoJson);

内容的提问来源于stack exchange,提问作者mohammad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 04:42:55