REST api with HttpClient but unknown JSON response - json

I'm using the WebApi httpclient to build up a .net api library for use against a REST webservice.
The rest service returns JSON.
Problem i am having is that for one request, it is possible that i get diffrent JSON formats back.
If the query was successful, I get back a JSON array which I have made a strong c# type to hold it.
Using the ReadAsAsync< T > method to get it out of the content.
If the request had a bad api key in or another error happens, the rest service returns a JSON object with some properties like status=error and an explanation message etc.
I cant then just use the ReadAsAsync< T > method as I dont know what format is comming back. I don't know much about the JSON linq library but is there a way I can put the JSON response into some JSON holder object and then check if there is a status=error in it and then use the correct deserialization to my strong type.
I seem to be able to store it in a JRaw object but don't know where to go from here.
Many thanks.

If the request had a bad api key in or another error happens, the rest service returns a JSON object with some properties like status=error and an explanation message etc.
In this case, the status code returned will not be successful. You can do a check on the status code and then deserialize your response content appropriately:
if (httpResponseMessage.IsSuccessStatusCode)
{
// Deserialize your JSON array
}
else
{
// Deserialize the error
}

You can use error handling in this case
try
{
//Deserialize your JSON Array..this will throw an exception in case of type mismatch
}
catch(Exception e)
{
//Deserialize your JSON object which will give you Error code or message
}

Related

Usage of Optional in unpredictable response from a web service

I'm using a web service to do some tasks. I have a problem in parsing the response of one of the APIs provided, which gives response as like below in different cases. The response code is 200 for both the cases.
A String(Not a JSON), when there are no records found in their database or invalid API version passed in the request URL.
A JSON, when the response is success(that is, in most of the cases)
So, I have gone with the below approach to fix this parsing issue. My doubt is, using Optional in this case, is right option or not?
// inside json parse utlity method
try {
// success
return Optional.of(objectMapper.readValue(responseBody, MyObject.class));
} catch(JsonParseException e) {
// when the response is not JSON. That is a `String`
return Optional.empty();
} catch(Exception e) {
throw new RuntimeException(e);
}
// do other stuff if value is present in Optional, otherwise skip
I'm using jackson library and Spring Boot REST service. If there is a better approach, please help me with that.

Angular 6 HttpClient not converting response to Interface

I have an api endpoint that responds with a JSON Array as a string.
Correspondingly, I have an interface that matches the JSON response
I have a service that makes the request to get the array of users and logs the first record to the console.
Expected Results
I expect to get a UserDetails object back and should print all the contents of index 0 to the console.
Actual Results
In the console I just see the character '['. It seems that res variable is still being treated as a string, and not a UserDetails array.
I have been struggling for house to try and figure out what is causing this behavior
I found the problem for anyone who is interested.
My server is returning the response in the body as a JSON string (this is a requirement from AWS API Gateway). The following has to be done to get the data to correctly parse.

restTemplate multi response structure

I need to call Rest web service using the GET method, the server will send 2 kind of response. when the request is processed with no business error it will send an object of type T. in case of business exception it will send an object of type E.
How can i call this web service using the restTemplate.getForEntity(url, responseType) method and receive a response with T type or E Type dynamically. because as you can see the method accept only one type.
In case of exception, the REST web service would be sending an error response, i.e. the code would not be 200, but 4** or 5**? If so, RestTemplate would use a DefaultResponseErrorHandler and throw an instance of HttpStatusCodeException with a method getResponseBodyAsString(). You can then use some converter to convert the string to a Java object.

JSON issue in Spring 3 and

I am using Spring 3.0 and ExtJS. I have been trying to send a Map object from my controller to jsp. When I putting a pojo in HashMap and sending that HashMap to view.
From controller it is returning a Map but in ExtJS it is not able to read the response and gives below error.
HTTP Error code: 406
message
description The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ().
Can anyone tell that how this can be resolved?
I dont think you can just shove any POJO into a map and return it via an HttpResponse. That's not how JSON works.
In order to send JSON from Java, you have to do the equivalent of serializing it using a JSON API (or roll your own). FlexJSON is one I use, as it ships in Spring Roo and is pretty easy.

springmvc handle the json request

I understand if I use springMVC and pass a json object to the controller, it will try to bind the json object to the controller pararmenter, but how to handle the binding error? I use something like this but seems not userful.
public String save(#RequestBody #Valid SomeList list, BindingResult result){
if(result.hasError()){
System.out.println(result);
}
}
Generally, you can return the same view that submitted the data. If you have <form:error> tags there, they will be displayed (because of the binding information).
But this is most certainly an ajax call, so what you can do is set a specific response status in the if body:
response.setStatus(HttpServletResponse.NOT_ACCEPTABLE);
and then look for that status code (406) in the ajax response handler. If you want precise validation information, you can try serializing the binding result itself as a response.
System.out.println will do next to nothing. Basically what it's saying is output the binding result to the server jvm std out.
Since you're returning a String, I'm going to assume you're returning a view name, so you might want to redirect the user to an error page.