I'm having an intermittent issue in MVC5 with the JSON parser throwing a System.InvalidOperationException:
Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Straight forward enough, but when I look at the request details, I have no idea why this would happen as the payload is very small:
(not sure how to scrape a raw request from chrome debugger, so):
The response is straightforward enough:
Any ideas on something a little less normal that might be causing this?
The problem was not in the size of the JSON request, but rather in the size of the JSON response.
return Json(model);
This the model was too large, and that's where the exception was coming from (why this wasn't raising in debug instance or logging the exception I'll have to look into...)
Related
Could you please explain Square's Retrofit response parsing logic.
I'm interested in case when we should receive & parse a big json (>100Kb) - will Retrofit wait while all content will be received from server and only than parse it, or it will start to parse it immediately while getting stream data?
My goal is to speedup response processing.
Are there any options about it available to configure?
As soon as the HTTP client parses the headers, the InputStream will be handed back to Retrofit which will then hand it directly to the Converter. This means that as the underlying converter mechanism (say, Gson) is pulling bytes they are being read (and potentially blocking) directly from the network.
Note: this is only true if logging is off (as it should be in production / release builds). When logging is turned on beyond HEADERS level, the response body has to be read in its entirety into a byte[] in order to both log and hand the data to the converter.
I have a webservice method that if I call directly via url GET returns XML without issue.
However, POST to that same url with Content-Type Json, it fails.
I think I can figure out the issue (I'm guessing it's an encoding or bad character somewhere in there) but I don't know how to debug the problem.
If I set a breakpoint in the webservice, it runs to completion. The failure appears to be happening AFTER the method returns, but BEFORE the json is returned to the caller.
How can I get in between to trace the error?
Please let me know if I can provide more context to help, but I really just need to know how to get in there.
EDIT:
The web service is configured to receive POST and return JSON and in fact DOES correctly return JSON in some cases. However, there are certain calls that are failing, so I need a way to trace this or debug it somehow and figure out why some calls are not working.
The web service is likely not configured to receive POST requests, especially if you are receiving a 405 Method Not Allowed response status.
Although I didn't find a way to debug or intercept the request to find the exact answer, it turns out the problem was the size of the content being returned by the webservice. Following this answer: ASP.NET WebMethod with jQuery json, is there a size limit?
and increasing the json limit fixed the issue!
Is there a way I could have trapped this to find the error without just guessing it was a size limit?
I would appreciate if someone could help me formulate a strategy for fixing the following error, which occurs in no discernible pattern; most of the time there is no error, and I am successful about 90% of the time:
ERROR [org.jboss.resteasy.core.SynchronousDispatcher] Failed executing POST /toys/customer25/insert
org.jboss.resteasy.plugins.providers.jaxb.JAXBUnmarshalException: Unexpected end of stream
How would I log this error simply to the console? I'd like to capture the JSON that this method is receiving and figure out what is causing this error. I would be able to see it in the server logs.
What I am doing is POSTing an array of Toy objects to the server, in JSON format. That is, on the client I transform my Toy object into a Toy JSON. The string that I am sending is like this: [{"toyName":"buzzlightyear", "toyMaker":"mattel"}]
My understanding is that when I POST JSON to a jax-rs restful service, a jax-rs implementation (I'm using RESTeasy 1.2) will somehow automagically convert that JSON string into a java Toy object.
My code on the Java JAX-RS restful service for handling a POST which inserts a Toy object is this:
#POST
#Consumes({MediaType.APPLICATION_JSON})
#Produces({MediaType.TEXT_PLAIN})
#Path("toy/{customer}/insert")
public String insertToys(#PathParam("customer") String customer, List<Toy> toys);
How do I log/capture what is wrong with the JSON string? It seems to me that the system is handling the conversion of the JSON to Toy object right when the insertToys() method is called. So it's hard form to figure out how to debug.
Can someone formulate a strategy for me? What is the likelihood that I am passing in malformed JSON, maybe from some unescaped character? Vs mapping entities wrong? Thanks!
Your JSON is incorrect.
The method accepts List, so you must send an array of Toy Objects:
[{"toyName":"buzzlightyear", "toyMaker":"mattel"}]
(note the braces).
For more objects:
[{"toyName":"buzzlightyear", "toyMaker":"mattel"},{"toyName":"rex", "toyMaker":"mattel"}]
Using Spring 3.0.5, I am trying to return a list of strings in JSON format.
I read the post spring-mvc-json-response
I have available to me jackson-mapper code 1.4.2 and it's on my classpath.
I am also using <context:component-scan base-package="com.funfun.foofoo2" /> which should satisfy the <mvc:annotation-driven> requirement.
I am returning a List<String> although I have tried just a bean too.
When I return raw JSON as a String, it works.
What is the following log output telling me? Is it saying it cannot find the Jackson JSON Mapper and thus the MappingJacksonHttpMessageConverter is not loaded?
17:19:01,037 DEBUG [AnnotationMethodHandlerExceptionResolver:132] Resolving exception from handler [com.funfun.foofoo2.CarModelsController#181fa4b]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
17:19:01,037 DEBUG [ResponseStatusExceptionResolver:132] Resolving exception from handler [com.funfun.foofoo2.CarModelsController#181fa4b]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
17:19:01,037 DEBUG [DefaultHandlerExceptionResolver:132] Resolving exception from handler [com.funfun.foofoo2.CarModelsController#181fa4b]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
17:19:01,053 DEBUG [DispatcherServlet:824] Null ModelAndView returned to DispatcherServlet with name 'appServlet': assuming HandlerAdapter completed request handling
Update: I am using jQuery's getJSON. In Firefox Firebug, I see the header coming over as application/json. The Spring method is constrained to only handle requests for JSON.
You need more than jackson-mapper, you need jackson-core as well, and preferably something newer than the rather old 1.4.x versions.
Basically what this exception (HttpMediaTypeNotAcceptableException) means is that the client is specifying an accepts header in their HTTP request, and it likely isn't accepting JSON. How are you making this request? AJAX call? If so, use Firebug or something to inspect the XHR and see what the accepts header is set to.
Just check the Accept param in your HTTP request header. If you are using XMLHttpRequest to make the ajax call, don't forget to change the requestHeader as follow:
xmlhttp.open("POST", custom_url, this.async);
xmlhttp.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml,application/json;q=0.9,*/*;q=0.8");
Regards,
David.
We are in the middle of a ongoing discussion about how to handle REST exceptions.
Response Content type : JSON
Two solutions we have:
Throw all the unchecked exceptions as a JSON response.
Send Request Invalid Response code.
Arguments:
When its a error, why return JSON? Just send a invalid response code.
Counter Argument:
Response code are too technical to handle for normal developers.
Whats your say??
For a JSON API I recently developed I do both. I always respond with valid JSON (well, assuming I respond at all). If I detect an invalid request, I use status 400. If I detect a server error (which I don't believe is caused by an invalid request), I use a 5xx status. The JSON object contains a special key that is only set for errors, with a string value.
I think this is a good solution that respects REST principles, and can be used in multiple ways. The same solution is used by some other JSON APIs, such as Yahoo Search. Try http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&output=json .
Use error codes like for HTTP. So 50* for any exception cause by some internal problem. And 40* for bad arguments. Avoid using your own defined codes as far as its possible. The idea is to have a "uniform" interface.
In general.
204 for success without sending any content
200 for success with a json representation of the resource
And if its not a successful operation return appropriate response code. You can choose to optionally return a json. To simplify things you can have a common format (json) for all error responses.
http://en.wikipedia.org/wiki/REST is a must read before you freeze on your api specs.