0

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?

values_wh
  • 71
  • 1
  • 6
  • 1
    Does this answer your question? [Deserialize JSON into C# dynamic object?](https://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object) – BurnsBA Sep 02 '22 at 13:17
  • Does this answer your question? [How can I deserialize JSON with C#?](https://stackoverflow.com/questions/6620165/how-can-i-deserialize-json-with-c) – Charlieface Sep 02 '22 at 13:35

2 Answers2

2

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);
}
Charlieface
  • 52,284
  • 6
  • 19
  • 43
0

Use late binding with the dynamic type:

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

var error = response.error;
Drunken Code Monkey
  • 1,796
  • 1
  • 14
  • 18