遍历JSON数组并将项目添加到列表C# [英] Looping through JSON array and adding items to list C#

查看:214
本文介绍了遍历JSON数组并将项目添加到列表C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,我是个初学者,试图找到我的问题,但没能

Sorry for basic question, I'm beginner and tried to find my problem, but wasn't able to

string json = "{\"EmailList\":[{\"name\":\"John Bravo\",\"email\":\"email@gmail.com\"},{\"name\":\"Daniel Alutcher\",\"email\":\"email@gmail.com\"},{\"name\":\"James Rodriguez\",\"email\":\"email@gmail.com\"}]}";

JObject rss = JObject.Parse(json);

var data = JsonConvert.DeserializeObject<dynamic>(json);

dynamic emails = data.EmailList;

List<string> emailList = new List<string>();

foreach (dynamic item in emails)
{
    int x = 0;
    if (item.email != null)
    {
        Console.WriteLine(item.email);
        //emailList.Add(item.email); // throws exception System.Collections.Generic.List<string>.Add(string)' has some invalid arguments' 
    }
}

所以我通过这个JSON循环,我可以在控制台中获取每封电子邮件,但是当我尝试将其添加到列表中时,会引发异常错误

So I'm looping trough this JSON and I'm able to get in console each email, but when I'm trying to add it to a list, it's throwing exception error

推荐答案

正如您评论"IS可以通过任何方式避免动态"在此代码中?" .

好吧,这很简单,这是过去的简单复制!
在Visual Studio中,使用顶部栏中特殊的过去菜单(图像).
或使用 app.quicktype.io

Well there is and it's pretty simple, It's a simple copy past!
In Visual Studio using the special past in top bar menu (image).
Or in an online tool like app.quicktype.io or json2csharp.com.

using  Newtonsoft.Json;

public partial class JsonData //Give it a better name
{
       [JsonProperty("EmailList")] public List<EmailInformation> EmailList { get; set; }
}

public partial class EmailInformation
{
       [JsonProperty("name")]  public string Name { get; set; } 
       [JsonProperty("email")] public string Email { get; set; }
}

用法也非常简单,并且您的代码中已经包含了大部分内容:

And the usage is pretty straightforward too, and you already have most of it in your code:

var data = JsonConvert.DeserializeObject<JsonData>(json);

foreach(var mailInfo  in data.EmailList){
       Console.WriteLine($"{mailInfo.Name} <{mailInfo.Email}>;");
}

//here a list of string 
var emails = data.EmailList.Select(x=> x.Email).ToList();

这篇关于遍历JSON数组并将项目添加到列表C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆