skip to Main Content

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


  1. You are trying to deserialise a collection of Letters objects to a single Letters 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>)

    var letters_requests = JsonConvert.DeserializeObject<List<Letters>>(json);
    

    You can also use Letters[] if this suits you more.

    Login or Signup to reply.
  2. Your Json file is incorrect, if a list of objects is stored there, then it should look like this:

    [
      {
        "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"
      }
    ]
    

    And deserialization should be like this:

    var letters_requests = JsonConvert.DeserializeObject<IEnumerable<Letters>>(json);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search