将JSON字符串解析为List< string>

问题描述:

string json = "{\"People\":[{\"FirstName\":\"Hans\",\"LastName\":\"Olo\"}
                            {\"FirstName\":\"Jimmy\",\"LastName\":\"Crackedcorn\"}]}";

var obj = JObject.Parse(json);

List<string> first;
List<string> last;

foreach (var child in obj["People"].Children())
{
    var name = child.First()["countryName"].ToString();
    var two = child.First()["countryCode"].ToString();
    var three = child.First()["isoAlpha3"].ToString();

    countries.Add(name);
    twoCharCodes.Add(two);
    threeCharCodes.Add(three);

    Console.Write("Name:\t\t{0}\n2CharCode:\t{1}\n3CharCode:\t{2}\n\n", name, two, three);
}

我正在寻找一种方法,将每个FirstName值添加到第一个List中,并与LastName vaues和最后一个List相同.最好的方法是什么?

I'm looking for a way to add each FirstName value into the first List and the same with the LastName vaues and the last List. What is the best way to go about doing this?

上面的代码中断于:

var name = child.First()["countryName"].ToString();

出现此错误:

 Cannot access child value on Newtonsoft.Json.Linq.JProperty

有什么建议吗?

这似乎是一种不好的方法(创建两个相关列表),但我假设您有自己的理由.

Seems like a bad way to do it (creating two correlated lists) but I'm assuming you have your reasons.

我将JSON字符串(在您的示例中有一个错字,它在两个对象之间缺少逗号)解析为一个强类型的对象,然后使用几个LINQ查询来获取两个列表.

I'd parse the JSON string (which has a typo in your example, it's missing a comma between the two objects) into a strongly-typed object and then use a couple of LINQ queries to get the two lists.

void Main()
{
    string json = "{\"People\":[{\"FirstName\":\"Hans\",\"LastName\":\"Olo\"},{\"FirstName\":\"Jimmy\",\"LastName\":\"Crackedcorn\"}]}";

    var result = JsonConvert.DeserializeObject<RootObject>(json);

    var firstNames = result.People.Select (p => p.FirstName).ToList();
    var lastNames = result.People.Select (p => p.LastName).ToList();
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class RootObject
{
    public List<Person> People { get; set; }
}