onlyo
onlyo

Reputation: 53

Looping through JSON array and adding items to list 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 protected]\"},{\"name\":\"Daniel Alutcher\",\"email\":\"[email protected]\"},{\"name\":\"James Rodriguez\",\"email\":\"[email protected]\"}]}";

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' 
    }
}

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

Upvotes: 0

Views: 2601

Answers (2)

Drag and Drop
Drag and Drop

Reputation: 2734

As you commented "IS there any way to avoid "dynamic" in this code?".

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();

Upvotes: 1

Mihir Dave
Mihir Dave

Reputation: 4014

You're Trying to add dynamic in List<string> instead you should do

emailList.Add(item.email.ToString()); 

Code:

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


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.ToString()); // Change here 
   }
}

Upvotes: 0

Related Questions