Java JSONObject error when deserializing with backslashes - java

I am running a Java Servlet webserver which receives the following request:
http://localhost:8080/ForVen/Recebimento/recebeDispositivo.jsp?lista={"dispositivo":[{"Id":0,"DataMod":"2021-09-28T16:55:55.3528819-03:00","SeSincronizar":0,"NrVersaoReg":1,"DataSincronizacao":"2021-09-28T16:55:55.3538812-03:00","Guid":"BFEBFBFF000206A7","TipoDispositivo":0,"URL":"","VendedorId":1}]}
When I send it, it gives me the following error:
javax.servlet.ServletException: org.json.JSONException: Missing value at character 1 of {"dispositivo":[{"Id":0,"DataMod":"2021-09-28T16:55:55.3528819-03:00","SeSincronizar":0,"NrVersaoReg":1,"DataSincronizacao":"2021-09-28T16:55:55.3538812-03:00","Guid":"BFEBFBFF000206A7","TipoDispositivo":0,"URL":"","VendedorId":1}]}
If I try to send the same request, but with the JSON "formatted", it works.
http://localhost:8080/ForVen/Recebimento/recebeDispositivo.jsp?lista={"dispositivo":[{"Id":0,"DataMod":"2021-09-28T16:55:55.3528819-03:00","SeSincronizar":0,"NrVersaoReg":1,"DataSincronizacao":"2021-09-28T16:55:55.3538812-03:00","Guid":"BFEBFBFF000206A7","TipoDispositivo":0,"URL":"","VendedorId":1}]}
This is the way I am deserializing the JSON:
JSONObject jso = new JSONObject(myIncomingJson);
I don't know if it has something to do with some Apache configuration, but I hope so, it would be extremely painful to change all of the client-side requests.

As f1sh said, I have to encode the JSON that is being send on the URL, my mistake that I didn't saw it. :)
This is how the URL should be:
http://192.168.1.58:8080/ForVen/Recebimento/recebeDispositivo.jsp?lista=%7B%5C%22dispositivo%5C%22%3A%5B%7B%5C%22Id%5C%22%3A0%2C%5C%22DataMod%5C%22%3A%5C%222021-09-30T09%3A15%3A37.4138271-03%3A00%5C%22%2C%5C%22SeSincronizar%5C%22%3A0%2C%5C%22NrVersaoReg%5C%22%3A1%2C%5C%22DataSincronizacao%5C%22%3A%5C%222021-09-30T09%3A15%3A37.4148274-03%3A00%5C%22%2C%5C%22Guid%5C%22%3A%5C%22BFEBFBFF000206A7%5C%22%2C%5C%22TipoDispositivo%5C%22%3A0%2C%5C%22URL%5C%22%3A%5C%22%5C%22%2C%5C%22VendedorId%5C%22%3A1%7D%5D%7D

Related

Jetty servlet: How can I forward GET request with parameters as POST request with JSON body?

My web clients send GET requests with URL query parameters. The receiving App can only accept POST requests with JSON body. I would like to embed a jetty servlet to the receiving App which converts GET requests to POST request, with url parameters being converted to json format body.
Input GET url for example: http://localhost:8081/?key_1=value_1&key_2=3value_2...&key_n=value_n
Expected POST json payload: {"key_1":"value_1", "key_2":"value_2", ..."key_n":"value_n"}
Could you please illustrate how to implement such functions?
I`ve worked with other programming languages, but am completely new to java. I really really appreciate your help.
Thanks and best regards,
Fischlein
You can read all the query string parameter and put it into HashMap. Then serialize this hashmap using jackson-json api or google gson api.
Jackson Reference Url :
http://wiki.fasterxml.com/JacksonHome
Read the parameters from the get request, create a json string and post it with a utility library like http://hc.apache.org/httpclient-3.x/

Why am I getting gson Exception: Expecting object found?

I am using the GSON API 1.7.1 sometimes having following error. Is there a bug for this version? Do I need to upgrade the current version 2.x.x
com.google.gson.JsonParseException: Expecting object found: "<!DOCTYPE"
at com.google.gson.JsonObjectDeserializationVisitor.visitFieldUsingCustomHandler(JsonObjectDeserializationVisitor.java:100)
at com.google.gson.ReflectingFieldNavigator.visitFieldsReflectively(ReflectingFieldNavigator.java:63)
at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:120)
at com.google.gson.JsonDeserializationContextDefault.fromJsonPrimitive(JsonDeserializationContextDefault.java:85)
at com.google.gson.JsonDeserializationContextDefault.deserialize(JsonDeserializationContextDefault.java:56)
The server is google push notification server GCM,
Here is my client code.
Gson gson = new Gson();
com.sun.jersey.api.client.ClientResponse webResponse=
resource.header("Authorization", authorizationKey).
header("Content-Type", MediaType.APPLICATION_JSON).
post(com.sun.jersey.api.client.ClientResponse.class, payloadStr);
String responsePayload = webResponse.getEntity(String.class);
GcmResponse response = gson.fromJson(responsePayload, GcmResponse.class); ===>>> Exception point
Is there a bug for this version?
No. Looks like your server is returning a non-JSON response or you're passing wrong parameters, this has nothing to do with the version you're using.
Try to check if the server is working as expected and is returning a JSON.
<!DOCTYPE is not valid Json; your server sometimes sends the wrong messages to your client. Since your client works 99% of the time, the problem is clearly in the server somehow, not the client.
However, since you've only provided us information here from the client side, there isn't enough for us to fix the problem. The best thing to do would be to attempt to capture the complete error message, then use searches or post a different question "Why does my android-scm server send messages that begin with <!DOCTYPE when they should be Json?"
To capture this complete errant message, I would do:
if(response.startsWith("<!DOCTYPE")) {
someLoggingMethod(response);`
} else {
// process the response

How to send a unix path as part of a JSON object to a web service via GET

Sorry if this is a duplicate question but google isn't smart enough to understand me or I'm too dumb to express my question simple enough for it to understand.
I don't know if this is my problem but I'm 90% sure this is it.
I'd like to know how to represent a Unix path within a GET request so that my web service doesn't return a 404. I think it's because one of my JSON fields in the query is a Unix path and because of the slashes, the webservice thinks it's part of the URL and not a part of my query.
For example, I'm using a RESTClient that's an add-on to Mozilla to test my web service. For the POST request, I enter as the url
http://mytestserver:8080/mydir/
and in the body, I put in my JSON object
{"filename":"obit.jpg", "Path":"test/2/1"}
This method works fine. I get a status code 200 and a return JSON object with the expected output.
When I use the same string for a GET request, I get a status code 404 and no return JSON object. I put as the url in the RESTClient
http://mytestserver:8080/mydir/{"filename":"obit.jpg", "Path":"test/2/1"}
and I get a status code 404 and the response body just says 404 - Not found
To further test my theory, I entered the following url in a GET request, removing the /2/1 from the path, which works.
http://mytestserver:8080/mydir/{"filename":"obit.jpg", "Path":"test"}
I've tried encapsulating the whole JSON string in quotes but that didn't work either so I've run out of things to try.
Thanks in advance for any help you can give me. If I need to show some code, please let me know, although, I don't think it's a code problem, I think it's a representation problem. Thanks.
Found out that JSON objects are usually sent via POST, not GET. Since I appended it to the URL via GET, it gave me problems. Per How to send a GET request with a "/" in the query

Java Jersey Jettison Message Body Reader Exception

I am a complete beginner at REST services but I need to access some information via REST from a web site. The service has some sample code to show how to login that I have used. The sample code uses Jettison as a JSON parser but when I try to run the following code snippet I get an Exception:
JSONObject post = baseResource.path("login")
.queryParam("service", "ABC").queryParam("auth", authParam)
.accept(MediaType.APPLICATION_JSON_TYPE).post(JSONObject.class);
baseResourse is a WebResource object. The code fails with the following exception:
Exception in thread "main" com.sun.jersey.api.client.ClientHandlerException:
A message body reader for Java class org.codehaus.jettison.json.JSONObject, and
Java type class org.codehaus.jettison.json.JSONObject, and MIME media type
application/json; character=utf-8 was not found
The sample code does not suggest that I should need to add any "message body readers" to handle the response? Or do I need to add or do anything obvious to parse the response? Thanks.
You need to include jersey-json module on your classpath. See http://jersey.java.net/nonav/documentation/latest/chapter_deps.html#d4e1817

Send error message as JSON object

I have two servlet: first servlet is similar to a client and creates an HttpURLConnection to call the second servlet.
I would like send a special error, formatted like a JSON object, so I call sendError method in this way:
response.sendError(code, "{json-object}")
But in the first servlet when I read error with getResponseMessage method I just get standard HTTP message and not my json object as a string.
How I can get my json string?
From the HttpServletResponse#sendError() javadoc:
The server defaults to creating the response to look like an HTML-formatted server error page containing the specified message, setting the content type to "text/html", leaving cookies and other headers unmodified. If an error-page declaration has been made for the web application corresponding to the status code passed in, it will be served back in preference to the suggested msg parameter.
So with this approach you have no other option than extracting the message from the HTML response yourself. JSoup may however be useful in this.
To achieve what you want, you need to set the error code and write the response yourself, e.g.
response.setStatus(code);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Instead of code you could by the way also use one of the HttpServletResponse.SC_XXX constants for this.

Categories