Reputation: 6762
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
Upvotes: 0
Views: 1747
Reputation: 1058
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.
}
Upvotes: 0
Reputation: 117057
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.
Upvotes: 4