skip to Main Content

Example JSON, for example say I want the quote and author values. I wasn’t able to get them unless I built a model around the JSON, which I’m not wanted to do as it would be more time consuming.

{
    "success": {
        "total": 1
    },
    "contents": {
        "quotes": [
            {
                "quote": "Plant your own garden and decorate your own soul, instead of waiting for someone to bring you flowers.",
                "length": "102",
                "author": "Veronica A. Shoffstall",
                "tags": [
                    "flowers",
                    "inspire",
                    "self-help",
                    "soul"
                ],
                "category": "inspire",
                "language": "en",
                "date": "2022-12-22",
                "permalink": "https://theysaidso.com/quote/veronica-a-shoffstall-plant-your-own-garden-and-decorate-your-own-soul-instead-o",
                "id": "LQbKQGxVA2rcH4lIwn6OIweF",
                "background": "https://theysaidso.com/img/qod/qod-inspire.jpg",
                "title": "Inspiring Quote of the day"
            }
        ]
    },
    "baseurl": "https://theysaidso.com",
    "copyright": {
        "year": 2024,
        "url": "https://theysaidso.com"
    }
}

My test example code with URL below. I tried it with Dynamic Object but can never get to the string.

try
        {
            private static readonly HttpClient _httpClient = new HttpClient();
            // Make the API request
            var response = _httpClient.GetAsync("https://quotes.rest/qod?language=en").Result;
           response.EnsureSuccessStatusCode();

            // Do something with the response
            var value11 = response.Content.ReadAsStringAsync().Result;
            var gett = JsonConvert.DeserializeObject<dynamic>(value11);
            var quote= gett.contents.quotes.quote;
            
            


            return quote;
        }
        catch (Exception ex)
        {
            quote = ex.Message;
            return quote;
        }

2

Answers


  1. Looking at the JSON structure the quotes property is an array and as such you should use

    var quote = gett.contents.quotes[0].quote;
    

    Assuming that deserialization was not the cause of the failure.

    Login or Signup to reply.
  2. There is no json convert error. quotes is array you can access gett .contents.quotes[0].quote.

    Tips; you don’t need to json convert and ReadAsString you can easily use like response.Content.ReadFromJsonAsync().Result?.contents.quotes[0].quote

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search