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

C#反序列化本地JSON文件时遭遇Unexpected character解析异常求助

解决JSON反序列化报错:Unexpected character encountered while parsing value: G. Path '', line 0, position 0

兄弟,我一眼就揪出你代码里的问题了!你遇到的这个报错,核心原因太典型了——你在JsonConvert.DeserializeObject<City.values>(filepath)这里,把文件路径字符串直接传给了反序列化方法,而不是JSON文件的实际内容!路径开头的盘符字符(比如G)被当成JSON的第一个字符来解析,这肯定会报错啊!

而且你的代码逻辑还有个问题:你用File.ReadLines逐行读取JSON文件,然后又去反序列化整个路径,这完全是南辕北辙——JSON是一个完整的结构化数据,单独的一行(比如只包含"id"的行)根本不是有效的JSON格式,逐行处理也没必要。

给你两个修复方案,按需选择:

方案一:读取整个JSON文件并反序列化(适合文件不大的情况)

先把整个JSON文件的内容读出来,再反序列化为对应的集合类型(city.list.json一般是城市数组,所以应该用List<City>而不是单个City.values):

using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;

// 先确保你的City类和JSON字段匹配,比如:
public class City
{
    public int id { get; set; }
    public string name { get; set; }
    // 按需补充country、coord等其他JSON字段对应的属性
}

// 修复后的核心代码
string filepath = Path.Combine(Application.StartupPath, "city.list.json");

// 读取整个JSON文件内容
string jsonContent = File.ReadAllText(filepath);

// 反序列化为城市列表
List<City> allCities = JsonConvert.DeserializeObject<List<City>>(jsonContent);

// 现在可以遍历列表处理你需要的id和name
foreach (var city in allCities)
{
    // 这里按你的需求过滤或处理
    if (!string.IsNullOrEmpty(city.name))
    {
        // 比如输出或存储城市信息
        // Console.WriteLine($"城市ID:{city.id},名称:{city.name}");
    }
}

方案二:流式读取反序列化(适合超大JSON文件,节省内存)

如果你的city.list.json特别大,用ReadAllText会占用太多内存,那就用流式读取的方式,逐对象解析:

using Newtonsoft.Json;
using System.IO;
using System.Windows.Forms;

// 同样确保City类定义正确
public class City
{
    public int id { get; set; }
    public string name { get; set; }
}

// 流式读取代码
string filepath = Path.Combine(Application.StartupPath, "city.list.json");

using (var streamReader = new StreamReader(filepath))
using (var jsonReader = new JsonTextReader(streamReader))
{
    var serializer = new JsonSerializer();
    
    // 遍历JSON数组中的每个城市对象
    while (jsonReader.Read())
    {
        if (jsonReader.TokenType == JsonToken.StartObject)
        {
            City city = serializer.Deserialize<City>(jsonReader);
            // 处理单个城市的逻辑
            if (city.id > 0 && !string.IsNullOrEmpty(city.name))
            {
                // do something
            }
        }
    }
}

额外注意点

  • 确保你的City类属性和JSON文件里的字段完全匹配(包括大小写),如果JSON是驼峰式(比如"id")而C#用帕斯卡式(比如Id),可以用[JsonProperty("id")]特性来映射:
    public class City
    {
        [JsonProperty("id")]
        public int Id { get; set; }
        
        [JsonProperty("name")]
        public string Name { get; set; }
    }
    
  • 一定要用Path.Combine拼接路径,避免因为分隔符问题导致文件找不到的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:33:09