【问题标题】:How to put the object I get from input in an JSON array?如何将我从输入中获得的对象放入 JSON 数组中?
【发布时间】:2021-12-18 01:52:59
【问题描述】:

我正在做一个天气预报控制台应用程序。我询问用户是否要保存输入位置。当他们输入经度和纬度时,它会保存在 JSON 文件中,因此稍后(第二次尝试)他们可以从列表中选择城市。问题是当城市对象保存在 JSON 文件中时,它不在数组中,这就是为什么后来我没有显示列表的原因。

程序.cs

//saving city objcet in JSON file
            if (userLoc == 1)
            {
                IConfiguration citConfiguration = new Configuration("cities.json");
                var CitiesConfig = new City()
                {
                    Id = 1,
                    CityName = $"{weatherInfo.Timezone}",
                    Lng = weatherInfo.Longitude,
                    Lat = weatherInfo.Latitude
                };
                citConfiguration.SetConfigs(CitiesConfig);
            }

City.cs

using Weather.PCL.Models.Abstractions;
using Configs.Models.Abstractions;

namespace Weather.PCL.Models.Implementations
{
    public class City : ICity, IConfig
    {
        public int Id { get; set; }
        public string CityName { get; set; }
        public double Lng { get; set; }
        public double Lat { get; set; }
    }
}

设置配置

public bool SetConfigs(IConfig config)
    {
        try
        {
            using (StreamWriter sw = new StreamWriter(_path))
            {
                var json = JsonConvert.SerializeObject(config);
                sw.Write(json);

                sw.Close();
                return true;
            }
        }
        catch (Exception ex)
        {
            return false;
        }
    }

在 JSON 文件中显示城市列表

var citiesJson = configuration.GetConfigs();
                var citiesArray = JsonConvert.DeserializeObject<City[]>(citiesJson);

                foreach (var item in citiesArray)
                {
                    Console.WriteLine(item.Id + ". " + item.CityName);
                }

当我运行项目时,我得到一个异常Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'Weather.PCL.Models.Implementations.City[]'

我能做什么?

【问题讨论】:

  • 您正在将一个对象反序列化为数组...提供 json 以获得明确的答案
  • json 一开始是空的
  • 如果你希望它为空,你的 json 应该是 []。不能是{}

标签: c# arrays json object config


【解决方案1】:

您的 JSON 字符串不包含 JSON 数组。 确保您的 JSON 字符串如下所示:[{"aaa":"a1","bbb":"b1","ccc":null},{"aaa":"a2","bbb":"b2","ccc":null}]

【讨论】:

  • 如果 JSON 文件为空,它只会保存一个新城市,所以这无济于事
  • 你得到的错误表明我在说什么,但这取决于你,当然,信不信由你。:)
【解决方案2】:

您必须创建一系列城市,而不是一个城市

 var CitiesConfig = new City[] {  
        new City
                {
                    Id = 1,
                    CityName = $"{weatherInfo.Timezone}",
                    Lng = weatherInfo.Longitude,
                    Lat = weatherInfo.Latitude
                }
               };

public bool SetConfigs(City[] config)
    {
        try
        {
            using (StreamWriter sw = new StreamWriter(@"cities.json"))
            {
                var json = JsonConvert.SerializeObject(config);
                sw.Write(json);

                sw.Close();
                return true;
            }
        }
        catch (Exception ex)
        {
            return false;
        }
    }

测试

string json = string.Empty;
    using (StreamReader r = new StreamReader(@"cities.json"))
        json = r.ReadToEnd();
        
    var citiesArray = JsonConvert.DeserializeObject<City[]>(json);

    foreach (var item in citiesArray)
    {
        Console.WriteLine(item.Id + ". " + item.CityName);
    }

【讨论】:

    猜你喜欢
    • 2021-07-18
    • 2021-08-22
    • 2016-08-06
    • 1970-01-01
    • 2019-01-06
    • 2020-06-30
    • 2020-10-20
    • 1970-01-01
    • 2021-08-29
    相关资源
    最近更新 更多