我正在做一个天气预报控制台应用程序。我询问用户是否要保存输入位置。当他们输入经度和纬度时,它会保存在JSON文件中,所以稍后(第二次尝试(他们可以从列表中选择城市。问题是,当city对象保存在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);
}
城市.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字符串如下所示:[{"aaa":"a1","bbb":"b1","ccc":null},{"aaa":"a2","bbb":"b2","ccc":null}]
您必须创建城市阵列,而不是一个城市
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);
}