Home > other >  Pass response data from RestSharp to JSON Properties
Pass response data from RestSharp to JSON Properties

Time:12-12

I am new to API, RestSharp and JSON. I got the Response Data from the API, my problem is I didn't know how to pass the response data to JSON Properties that I've been readied.

Here is my Code.

This is the API response I received.

{
  "data": {
    "id": "link_4txtnKwrBbTTQfRwswSLcinw",
    "type": "link",
    "attributes": {
      "amount": 65656,
      "archived": false,
      "currency": "USD",
      "description": "2323",
      "livemode": false,
      "fee": 0,
      "remarks": "12321",
      "status": "unpaid",
      "tax_amount": null,
      "taxes": [],
      "checkout_url": "https://pm.link/------",
      "reference_number": "sadXlwd",
      "created_at": 1670820915,
      "updated_at": 1670820915,
      "payments": []
    }
  }
}

RestSharp Code: Click here to view

The variables that I want to fill with RestSharp Response Contents Click here to view

I tried this code, but it still returns no results.

var model = JsonConvert.DeserializeObject<Attributes>(response.Content);
string value = model.CheckoutUrl;

I expect to populate the attributes class with the contents of RestResponse.

CodePudding user response:

Try and check the response variable first if it contains any json data, or check its response. You have no handling for failed responses as well, you are only considering the OK response.

CodePudding user response:

you will have to create a root class and use it to deserialize your json

Model model = JsonConvert.DeserializeObject<Model>(response.Content);

string value = model.Data.Attributes.CheckoutUrl;


     public partial class Model
    {
        [JsonProperty("data")]
        public Data data { get; set; }
    }

    public partial class Data
    {
        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("attributes")]
        public Attributes Attributes { get; set; }
    }

or if you only need attributes data, you can do it without the extra classes

Attributes attributes = JObject.Parse(response.Content)["Data"]["Attributes"].ToObject<Attributes>();

string checkoutUrl = attributes.CheckoutUrl;
  • Related