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

1
  • 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. Commented Jun 30, 2021 at 7:20

3 Answers 3

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
    }
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Please explain your code (even explanatory code comments are helpful).
0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.