前言
一个看起来很莫名其妙的错误, json文件我打开看了下, 格式也都正确,
但是在vs中调试的时候, 监视 -- 查看 -- JSON可视化工具
查看json字符串的话,
会提示"字符串未设置为JSON格式",
"监视 -- 查看 -- 文本可视化工具", 发现json格式确实看不出来任何问题.

报错
var geoJsonObject = JObject.Parse(geoJson);
Newtonsoft.Json.JsonReaderException:“Unexpected end of content while loading JObject. Path 'features[1962]', line 1967, position 7249.”
解决方案
我这个json文件是通过GDAL生成出来的, 而我生成出来后, 并没有把相关资源关闭,
猜测可能会导致缓冲区中的数据未正确刷新到磁盘,这可能使得文件的部分内容丢失或不完整?
错误代码↓
# 错误代码
public static bool Convert2GeoJSONFile(string shpFilePath, string geoJSONFilePath)
{
bool isOk = false;
GdalConfiguration.ConfigureGdal();
GdalConfiguration.ConfigureOgr();
if (string.IsNullOrWhiteSpace(shpFilePath) || string.IsNullOrWhiteSpace(geoJSONFilePath))
{
throw new ArgumentException("输入参数路径不合法");
}
OSGeo.GDAL.Gdal.AllRegister();
OSGeo.OGR.Ogr.RegisterAll();
OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", "");
Gdal.SetConfigOption("DXF_ENCODING", "UTF-8");
DataSource ds = Ogr.Open(shpFilePath, 0);
if (ds == null)
{
throw new Exception($"打开文件失败{shpFilePath}");
}
using OSGeo.OGR.Driver dv = Ogr.GetDriverByName("GeoJSON");
if (dv == null)
{
throw new Exception($"打开驱动失败:GeoJSON");
}
var ret = dv.CopyDataSource(ds, geoJSONFilePath, null);
isOk = true;
return isOk;
}
正确代码↓
public static bool Convert2GeoJSONFile(string shpFilePath, string geoJSONFilePath)
{
bool isOk = false;
GdalConfiguration.ConfigureGdal();
GdalConfiguration.ConfigureOgr();
if (string.IsNullOrWhiteSpace(shpFilePath) || string.IsNullOrWhiteSpace(geoJSONFilePath))
{
throw new ArgumentException("输入参数路径不合法");
}
OSGeo.GDAL.Gdal.AllRegister();
OSGeo.OGR.Ogr.RegisterAll();
OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", "");
Gdal.SetConfigOption("DXF_ENCODING", "UTF-8");
DataSource ds = Ogr.Open(shpFilePath, 0);
if (ds == null)
{
throw new Exception($"打开文件失败{shpFilePath}");
}
using OSGeo.OGR.Driver dv = Ogr.GetDriverByName("GeoJSON");
if (dv == null)
{
throw new Exception($"打开驱动失败:GeoJSON");
}
using var ret = dv.CopyDataSource(ds, geoJSONFilePath, null);
isOk = true;
return isOk;
}
摘抄文档
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了