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?
CodePudding user response:
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);
}
CodePudding user response:
Use late binding with the dynamic type:
dynamic response = JsonConvert.DeserializeObject("{\"error\":\"Error ID\",\"code\":\"invalid_id\"}");
var error = response.error;