0

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

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Tt11
  • 9
  • 3
  • Welcome to StackOverflow. Please bear in mind that C# is a case-sensitive language. So, please try to provide valid C# code, which can be compiled. – Peter Csala Jun 30 '21 at 07:20

3 Answers3

1

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
    }
Michael
  • 11
  • 3
  • This code will crash with `NullReferenceException`. The sample json contains a field called `result`. Your `Result` class defines a property (`Results`) which is not present in the json, that's why it will be null. The app will fail when it reaches foreach. Please fix your proposed solution. – Peter Csala Jun 30 '21 at 07:26
  • Please explain your code (even explanatory code comments are helpful). – Connor Low Jun 30 '21 at 16:37
0

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

PVA
  • 24
  • 2
0

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>.

MartinM43
  • 101
  • 1
  • 1
  • 8