Search code examples
c#jsonasp.net-web-apijson-deserialization

Get response by web api a json string and print only one of the values


I call an API that returns a JSON string like this one:

{ 
    "type": "success", 
    "value": 
    { 
        "id": 246, 
        "joke": "Random joke here...", 
        "categories": [] 
    } 
}

I want to make my program read the JSON string and return only the joke string. I was able to get the string from the Web API but I can't make it to JSON object so I can print only the joke string.


Solution

  • First you'll need to create the classes to deserialize your json into. For this you can use VS's Edit -> Paste Special -> Paste Json As Classes or use a website like JsonUtils:

    public class JokeInfo
    {
    
        [JsonProperty("id")]
        public int Id { get; set; }
    
        [JsonProperty("joke")]
        public string Joke { get; set; }
    
        [JsonProperty("categories")]
        public IList<string> Categories { get; set; }
    }
    
    public class ServerResponse
    {
    
        [JsonProperty("type")]
        public string Type { get; set; }
    
        [JsonProperty("value")]
        public JokeInfo JokeInfo { get; set; }
    }
    

    Then use a library like JSON.NET to deserialize the data:

    // jokeJsonString is the response you get from the server
    var serverResponse = JsonConvert.DeserializeObject<ServerResponse>(jokeJsonString);
    // Then you can access the content like this:
    
    var theJoke = serverResponse.JokeInfo.Joke;