Tt11
Tt11

Reputation: 9

How to Loop through serialized json

Res={"result":["123","563"]}

This is the similar json file i have. I have to loop through it and assign each value as ids. I am trying as

Obj = JsonConvert.DeseraializeObject<classname>(Res);
Foreach(string id in Obj)
{Function();}

I'm getting error as class doesn't have extension for getenumerator

Edit:
I did this

List<classname> objlist = jsonconvert.deserializeObject<list<classname>>(res); 
foreach (string id in objlist)
{function();}

getting an error for foreach loop as cannot convert classname to string

Upvotes: 0

Views: 1360

Answers (3)

Michael
Michael

Reputation: 11

In JSON file you have string array with key "results". It can be modelled like this:

public class Result
{
    public List<string> results { get; set; }
}

You can deserialize and then loop through it in the next way:

var data = JsonConvert.DeserializeObject<Result>(Res);
    foreach (var id in data.results)
    {
      // Assignment logic
    }

Upvotes: 1

MartinM43
MartinM43

Reputation: 101

Your Json structure looks something like this in c#

using Newtonsoft.Json;

public class Result
{ 
    [JsonProperty("result")]
    List<string> Res { get; set; }
}

Deserialze:

Result r = JsonConvert.DeserializeObject<Result>(jsonString);

Briefly explained: Your json has a property called "result", this property is a "list" of type "string" List<string>.

Upvotes: 0

PVA
PVA

Reputation: 24

Your object should have property List or List and you will iterate throw it, not in Obj.

Upvotes: 0

Related Questions