I want to iterate through a JSON file of this kind, using C#, and compare if the response is the same as the expected response.
Json
file:
{
"request": "AAA",
"response": "BBB",
"expected_response": "BBB"
}{
"request": "CCC",
"response": "DDD",
"expected_response": "DDD"
}{
"request": "EEE",
"response": "FFF",
"expected_response": "GGG"
}{
"request": "HHH",
"response": "III",
"expected_response": "III"
}{
"request": "LLL",
"response": "YYY",
"expected_response": "UUU"
}
To me it would make sense to do something like this:
public class Letters
{
public string request { get; set; }
public string response { get; set; }
public string expectedResponse { get; set; }
}
var json = System.IO.File.ReadAllText("path/to/json/file.json");
var letters_requests = JsonConvert.DeserializeObject<Letters>(json);
foreach (var letter in letters_requests)
{
if(letter.response == letter.expectedResponse)
// do something
}
However, it get the following error:
foreach statement cannot operate on variable of type 'Letters' because 'Letters' does not contain a public instance or extension definition for 'GetEnumerator'
.
Can someone explain me how can I achieve what I want? I’m really new to C#
Thank you
2
Answers
You are trying to deserialise a collection of
Letters
objects to a singleLetters
object. From your code intention you are trying to parse all the objects in your json file.Change your code to something like this: (assuming you want a
List<Letters>
)You can also use
Letters[]
if this suits you more.Your Json file is incorrect, if a list of objects is stored there, then it should look like this:
And deserialization should be like this: