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

如何将输入获取的对象存入JSON数组,解决C#天气应用反序列化报错

问题解决方法

错误原因

当前写入逻辑每次直接将单个City对象序列化为JSON写入文件,没有包裹在数组中,导致JSON结构是{}对象格式,而读取时尝试反序列化为[]数组格式,类型不匹配触发报错。

分步修改方案

1. 修改配置写入方法SetConfigs

调整逻辑:写入前先读取现有JSON文件中的城市数组,将新城市追加到数组后,再序列化整个数组覆盖写入文件,兼容首次写入文件不存在的场景:

public bool SetConfigs(IConfig config)
{
    try
    {
        List<City> cityList;
        // 先判断文件是否存在、是否有有效内容
        if (File.Exists(_path) && new FileInfo(_path).Length > 0)
        {
            // 读取已存的城市列表
            string existingJson = File.ReadAllText(_path);
            cityList = JsonConvert.DeserializeObject<List<City>>(existingJson) ?? new List<City>();
        }
        else
        {
            // 首次写入初始化空列表
            cityList = new List<City>();
        }
        // 将新城市加入列表
        cityList.Add((City)config);
        // 序列化整个列表写入文件
        using (StreamWriter sw = new StreamWriter(_path))
        {
            var json = JsonConvert.SerializeObject(cityList, Formatting.Indented);
            sw.Write(json);
            sw.Close();
        }
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

2. 修正Program.cs中城市Id赋值逻辑

不要写死Id为1,改为取现有列表最大Id+1,避免后续多城市Id重复:

if (userLoc == 1)
{
    IConfiguration citConfiguration = new Configuration("cities.json");
    List<City> existingCities = new List<City>();
    // 先读现有城市计算新Id
    if (File.Exists("cities.json") && new FileInfo("cities.json").Length > 0)
    {
        string json = File.ReadAllText("cities.json");
        existingCities = JsonConvert.DeserializeObject<List<City>>(json) ?? new List<City>();
    }
    int newId = existingCities.Any() ? existingCities.Max(c => c.Id) + 1 : 1;
    var CitiesConfig = new City()
    {
        Id = newId,
        CityName = $"{weatherInfo.Timezone}",
        Lng = weatherInfo.Longitude,
        Lat = weatherInfo.Latitude
    };
    citConfiguration.SetConfigs(CitiesConfig);
}

3. 读取逻辑适配优化(可选)

反序列化时用List<City>更灵活,避免数组长度固定的问题:

var citiesJson = configuration.GetConfigs();
var citiesArray = JsonConvert.DeserializeObject<List<City>>(citiesJson) ?? new List<City>();
foreach (var item in citiesArray)
{
    Console.WriteLine(item.Id + ". " + item.CityName);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 20:15:05