Home > Net >  How do you deserialize a JSON to get a string value without having to build an entire model? Below i
How do you deserialize a JSON to get a string value without having to build an entire model? Below i

Time:12-22

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;
        }

CodePudding user response:

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.

  • Related