Search code examples
c#json.net-corerestsharpweb-api-testing

How to get element value from response data to json


Im writing an API automation test with RestSharp.Any kind of help will be greatly appreciated! I'm getting data values from the response & I need to write few values to my json file (which I will use for another test putting them as a body). I managed to get 1 value from JArray but I need 2 more values and I cant wrap my head around how to do that. Im attaching my api test code & the data I get from the response + the data I managed to write into my json file.

The value that I managed to get: FsNumber (declared it as financialNumber). What I need to add to the json: subjectName + subjectCode (they will be declared as companyName/companyCode). How do I access "Query" list with SubjectName/SubjectCode?

TEST

var queryResult = client.Execute<object>(request);

var data = JsonConvert.SerializeObject(queryResult.Data);

var jsonParse = JToken.Parse(data);

var fsObject = jsonParse.Value<JToken>("FinanceReportList");
var fsArray = fsObject.Value<JArray>("List");

foreach (var fs in fsArray)
{
    var cfn = fs.Value<string>("FsNumber");

    var queryObject = new DataQuery
    {
        financialNumber = cfn,
    };

    var queryObjectString = JsonConvert.SerializeObject(queryObject);
    File.WriteAllText(@"C:\Users\TestAPI\myJsonWithValues.json", queryObjectString);
}

Data I get from the response:

{
  "RequestDate": "2021-07-16",
  "Message": "Active",
  "ProductNumber": 666,
  "Language": "EN",
  "RequestId": "reqID666",
  "Query": {
    "SubjectCode": "MY-SUBJECT",
    "SubjectName": "MY-NAME"
  },
  "FinanceReportList": {
    "List": [
      {
        "FsNumber": "MY-NUMBER",
        "Year": 2021,

So far I managed to get FsNumber to my myJsonWithValues.json file as this: {"financialNumber":"MY-NUMBER","companyName":null,"companyCode":null} What Im trying to do is, my json should look like {"financialNumber":"MY-NUMBER","companyName":MY-NAME,"companyCode":MY-CODE}


Solution

  • You have to access "Query" object

      var fsQuery = jsonParse.Value<JToken>("Query") 
    

    and use Children() method to access properties of "Query"

    var children = fsQuery.Children(); 
    

    It is a good practice to implement a class that encapsulates your resonse and deserialize it with JsonConvert.Deserialize eg.

    public class Account
    {
        public string Email { get; set; }
        public bool Active { get; set; }
        public DateTime CreatedDate { get; set; }
        public IList<string> Roles { get; set; }
    }
    
    Account account = JsonConvert.DeserializeObject<Account>(json);
    

    Instead of using JObjects