Deserializing JSON response using RestSharp



  • I'm looking for some general advice with an API framework I am setting up using C# and RestSharp as the client library. I've successfully set up an initial test, but I'm now looking at creating a series of assertions to ensure that certain values are returned in the response

    My test looks as below:

            [Test]
        public void ShouldHaveDataAttributes()
        {
            var restClient = new RestClient("http://ergast.com/api/f1");
    
            var restRequest = new RestRequest("2016/circuits.json", Method.GET);
    
            var restResponse = restClient.Execute(restRequest);
    
            dynamic jsonResponse = JsonConvert.DeserializeObject(restResponse.Content);
    
            dynamic jsonObject = jsonResponse.MRData.CircuitTable;
            int circuitId = (int)jsonObject.season;
            System.Console.WriteLine(jsonObject);
        }
    

    The jsonObject returns the below data:

    {
      "season": "2016",
      "Circuits": [
        {
          "circuitId": "albert_park",
          "url": "http://en.wikipedia.org/wiki/Melbourne_Grand_Prix_Circuit",
          "circuitName": "Albert Park Grand Prix Circuit",
          "Location": {
            "lat": "-37.8497",
            "long": "144.968",
            "locality": "Melbourne",
            "country": "Australia"
          }
        }]
    }
    

    My question is how would I specifically check that, for example the correct "circuitId" is returned or that the "circuitName" value is "Albert Park"? I'm keen to carry on utilising RestSharp for my framework so was hoping there was an extension to allow me to do that



  • Assuming the de-serialized class for the json looks something like below, the way to extract "circuitId": "albert_park" is follows:

    The code is not C#, but this can give an idea.

    List<Circuit> circuitList = example.getCircuits();
    circuitList.get(0).getCircuitId(); // this would return albert_park
    

    De-serialized model class:

    public class Example {
    
    private String season;
    private List<Circuit> circuits = null;
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();
    
    public String getSeason() {
    return season;
    }
    
    public void setSeason(String season) {
    this.season = season;
    }
    
    public List<Circuit> getCircuits() {
    return circuits;
    }
    
    public void setCircuits(List<Circuit> circuits) {
    this.circuits = circuits;
    }
    
    public Map<String, Object> getAdditionalProperties() {
    return this.additionalProperties;
    }
    
    public void setAdditionalProperty(String name, Object value) {
    this.additionalProperties.put(name, value);
    }
    
    }
    

    There would be a similar class for Circuit having its attributes.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2