0

I got the below JSON.Stringify data from ajax call to c# code. I am trying to loop through each country like. But I am unable to make countryList as List or array from resultant string from ajax call. String returned to controller is ["Germany","Brazil","United States"] while debugging but it is showing with reverse slashes and It fails reading in loop.

 foreach (var cntry in countryList){
//my code
}

I tried the below

enter image description here

enter image description here

1

2 Answers 2

4

Try parsing the JSON first. Here's how:

foreach (var cntry in Newtonsoft.Json.JsonConvert.DeserializeObject<string[]>(countryList))
{
    //my code
}

You need to NuGet "Newtonsoft.Json" to get this to work.

Sign up to request clarification or add additional context in comments.

2 Comments

any other option apart from getting Newtonsoft please?
@Kurkula - You would have to write a JSON parser yourself or use an external library.
0

Using System.Text.Json:

var countriesJsonAsString = "[\"Germany\", \"Brazil\", \"United States\"]";
foreach (var entry in System.Text.Json.JsonSerializer.Deserialize<List<string>>(countriesJsonAsString))
{
    // my code here, entry will contain the name of the country.
}

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.