values_wh
values_wh

Reputation: 93

How to parse a json response?

The answer comes to me like this json:

{"error":"Error ID","code":"invalid_id"}

I need to find out if there is an "error"/"errors" in the json response to throw an exception on an error. How to do it most optimally with the help of Newtonsoft.Json?

Upvotes: 0

Views: 90

Answers (2)

Rafael Reis
Rafael Reis

Reputation: 36

You should have a c# class that represents the json object.

For Example:

public class JsonResponse {
    [JsonProperty("Error")]
    public string ErrorMessage {get;set;}
    
    [JsonProperty("code")]
    public string ErrorCode {get;set;}

}

Then you can desserialize the jsonText into this class, and check if Error is null or empty:

var response = JsonConvert.Desserialize<JsonResponse>(jsonText);
if(!string.IsNullOrWhitespace(response.Error)) {
       Console.WriteLine("Ocorreu um erro: " + response.Error);
}

Upvotes: 2

Drunken Code Monkey
Drunken Code Monkey

Reputation: 1839

Use late binding with the dynamic type:

dynamic response = JsonConvert.DeserializeObject("{\"error\":\"Error ID\",\"code\":\"invalid_id\"}");

var error = response.error;

Upvotes: 0

Related Questions