[英]How to iterate through a List and convert it to a JSON object using JSON.NET (C# / ASP.NET)
[英]Convert Json into List<T> in C# using Json.NET
我有一個JSON字符串如下
private string jsonCountry = @"{'BD': '880', 'BE': '32', 'BF': '226', 'BG': '359', 'BA': '387', 'BB': '+1-246', 'WF': '681'};
我正在努力實現的目標
class Country
{
public string Countrypfx {get;set;}
public string CountryCode {get;set;}
}
public List<Country> GetData()
{
private string jsonCountry = @"{'BD': '880', 'BE': '32', 'BF': '226', 'BG': '359', 'BA': '387', 'BB': '+1-246', 'WF': '681'};
// Here, I want to return List<Country> object
}
我嘗試過的
public Country[] GetCountries()
{
MyCountryData myData = JsonConvert.DeserializeObject<MyCountryData>(jsonCountry);
Country[] countries = myData.data;
return countries;
}
public class Country
{
public string CountryPrefix { get; set; }
public string ContryCode { get; set; }
}
public class MyCountryData
{
public Country[] data { get; set; }
}
有人可以幫我獲得所需的輸出嗎? 謝謝
您的json格式不正確,無法直接將其轉換為列表。
首先,您必須將其轉換為字典
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonCountry);
然后將其轉換為所需的列表。
var countries = dict.Select(d => new Country { CountryPrefix = d.Key, CountryCode = d.Value });
這是將json轉換為自定義對象列表的方法:
string jsonCountry = @"{'BD': '880', 'BE': '32', 'BF': '226', 'BG': '359', 'BA': '387', 'BB': '+1-246', 'WF': '681'}";
MyCountryData conData = new MyCountryData();
conData.data = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonCountry)
.Select(x => new Country { CountryPrefix = x.Key, ContryCode = x.Value}).ToArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.