Home > OS >  How can I loop through API response in C#
How can I loop through API response in C#

Time:09-15

I have a response coming from API call, I want to loop through the response to display it on UI.

IRestResponse response = client.Execute(request);
string responseContent = response.Content;
[
  {
    "details": {
      "ID": "STUD_111",
      "language": "en",
      "PersonalInfo": {
        "lastName": "Dias",
        "firstName": "Peter"
      }
    },
    "Score": {
      "attemptes": { "numOfAtmpt": 1 },
      "marks": {
        "total": 100,
        "min": 30,
        "achieved": "55"
      },
      "grade": {
        "card": [
          {
            "gradeObtained": "B",
            "passingGrade": {
              "Min": "C",
              "Avg": "B",
              "Max": "A"
            }
          }
        ]
      }
    }
  }
]

I am getting above response in responseContent variable. Need a way to display above information on UI.

CodePudding user response:

step1: Create a Model based on your response using this https://json2csharp.com/

  public class Root
  {
    public Details Details { get; set; }
    public Score Score { get; set; }
  }

  public class Details
  {
    public string ID { get; set; }
    public string Language { get; set; }
    public PersonalInfo PersonalInfo { get; set; }
  }

  public class Score
  {
    public Attemptes Attemptes { get; set; }
    public Marks Marks { get; set; }
    public Grade Grade { get; set; }
  }

 public class PersonalInfo
 {
   public string LastName { get; set; }
   public string FirstName { get; set; }
 }

 public class Attemptes
 {
   public int NumOfAtmpt { get; set; }
 }

 public class Marks
 {
   public int Total { get; set; }
   public int Min { get; set; }
   public string Achieved { get; set; }
 }

public class Grade
{
  public List<Card> Card { get; set; }
}

public class Card
{
  public string GradeObtained { get; set; }
  public PassingGrade PassingGrade { get; set; }
}

public class PassingGrade
{
  public string Min { get; set; }
  public string Avg { get; set; }
  public string Max { get; set; }
}

STEP 2:

var response = JsonConvert.DeserializeObject<List<Root>>(jsonString);

STEP 3:

  foreach (var item in response)
  {
      //do your magic here
  }
  • Related