Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading