我正在做一個天氣預報控制臺應用程式。我詢問用戶是否要保存輸入位置。當他們輸入經度和緯度時,它會保存在 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[]'
我能做什么?
uj5u.com熱心網友回復:
您的 JSON 字串不包含 JSON 陣列。確保您的 JSON 字串如下所示:[{"aaa":"a1","bbb":"b1","ccc":null},{"aaa":"a2","bbb":"b2","ccc":null}]
uj5u.com熱心網友回復:
您必須創建一系列城市,而不是一個城市
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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/346676.html
