Can I post JSON format in AWS Lambda function? - java

I have a JSON file and I want to send it to the RequestHandler. The error response is the following:
java.util.LinkedHashMap cannot be cast to java.lang.String

You're attempting to send a LinkedHashMap, as the error and #Mark B says, to the RequestHandler. Instead, "stringify" it into a JSON string first.
I recommend one of two libraries for this.
Google's GSON library
String jsonString = new Gson().toJson(jsonData, LinkedHashMap.class);
Java's JSON library
String jsonString = new JSONObject(jsonData).toString()
Then, send this string to the RequestHandler. Hope this helps.

Related

Java parsing from escaped json string

There are many threads related to this, but I can't solve my issue.
I get this string from parsing an iterable using GSON.
Iterable<ParametrosProveedores> proveedoresList;
proveedoresList = proveedoresRepository.findAll(); //From spring repository
String jsonString = gson.toJson(proveedoresList);
jsonString value is:
[{\"id\":1,\"proveedor\":\"CALIXTA\",\"unaVia\":true,\"dosVias\":true,\"plazasSi\":\"todas\",\"plazasNo\":\"\",\"turnoUnaVia\":false,\"turnoDosVias\":false},{\"id\":2,\"proveedor\":\"MOVILE\",\"unaVia\":true,\"dosVias\":true,\"plazasSi\":\"51,52\",\"plazasNo\":\"\",\"turnoUnaVia\":false,\"turnoDosVias\":false},{\"id\":3,\"proveedor\":\"TWILIO\",\"unaVia\":true,\"dosVias\":true,\"plazasSi\":\"todas\",\"plazasNo\":\"51\",\"turnoUnaVia\":false,\"turnoDosVias\":false},{\"id\":4,\"proveedor\":\"OTRO\",\"unaVia\":true,\"dosVias\":true,\"plazasSi\":\"todas\",\"plazasNo\":\"\",\"turnoUnaVia\":false,\"turnoDosVias\":false}]
Which is a json array. Is there really no way to parse from that string without removing escapes manually?
All I want to do is:
JSONArray jsonArray = parseFrom(jsonString);
Is it possible?
Since you are using a generic in the form of an Iterable<T>, you may need to use:
String jsonString = gson.toJson(proveedoresList, typeOfSrc);
Where typeOfSrc is the type of your proveedoresList. that way gson knows how to serialize the object properly.

Jersey client send string with application/json type

I need to send a String that is already in JSON format using the Jersey client 1.19 and genson 1.3
Client.create().resource(path).webResource.type(MediaType.APPLICATION_JSON_TYPE)
.accept(MediaType.APPLICATION_JSON_TYPE).put(ClientResponse.class, jsonAsString)
The problem with this is that the client is parsing the string, I need it to be sent as it is.
I'm sending something like { "name":"Foo" } and the client is converting it to "{ \"name\":\"Foo\" }". If I change the type to PLAIN_TEXT it sends the request correctly but I need to send it as application/json .
So yes Genson will try to encode your string as a literal json string. In this case it is maybe not what you would want, but more generally it is what people would expect: serialize à java string as a json string.
The solution I see is too extend GensonJsonConverter and override isWritable to return false when the input type is string. Then just register it. That should work.
I've opened this issue so it can be added as a more flexible feature.
Try changing MediaType.APPLICATION_JSON_TYPE to MediaType.APPLICATION_JSON
http://examples.javacodegeeks.com/enterprise-java/rest/jersey/json-example-with-jersey-jackson/
I tried your code with Jersey 1.19, Genson 1.3 and Wireshark. It works fine without Genson so it appears Genson is treating it as a literal string (since it is of type String) and therefore quoting the double quotes.
The following works.
String jsonAsString = "{ \"name\":\"Foo\" }";
Map<String, String> map = (new Genson()).deserialize(jsonAsString, Map.class);
String path = "...";
ClientResponse resp =
Client.create().resource(path)
.type(MediaType.APPLICATION_JSON_TYPE)
.accept(MediaType.APPLICATION_JSON_TYPE)
.put(ClientResponse.class, map);
I have used Map because it is sufficient for the example but you can deserialize it to the appropriate object.
If you looking for an option to specify that the string should be passed as is, I am not yet aware of it but this should at least provide a solution to the problem of sending that string as application/json.

Decode json object to string android

I used json_encode(); to convert string to json in php and then response it to android but I can't use the response, how can I convert the json to string?
when I display the response it shows this :
"{\n'OK': \n[\n{\n'Name': 'MyName',\n'Gender':'Male'\n}\n]\n}"
what shall I do?
thank you
Since you're just converting a string to json, you're not returning a JSONObject or JSONArray, according to: http://php.net/manual/en/function.json-decode.php
If you must return a string, you may have to use some json library or write your own parser.
If that doesn't sound appealing, I recommending returning a JSONObject or JSONArray with one element.
For example:
php
echo json_encode( array('result' => 'the string you are encoding') );
java
JSONObject json = new JSONObject( encodedStringResponseFromPhp );
String theStringYouEncoded = (String) json.get( "result" );
You'll need to add a throws JSONException to the function you add this java code too or put it inside a try catch block.
Have you tried using a JSON-Library like https://code.google.com/p/json-simple/? Looks like you need some help decoding the string.
Edit: You should use the json2.js library from Douglas Crockford. It provides some extra features and better/older browser support.
Read more...

How to convert Java Object to JSON string?

Hello i'm trying to convert my Java Object to a Json string to use in my view with javascript functions.
I tried to use Google's gson lib:
String myjson = "";
Gson gson = new Gson();
myjson = gson.toJson(myuser);//myuser is my java object
However when i call myjson, it consists of '"' instead of the character '"' for this reason i can't able to use it in my view, it is creating me problems.
How can I fix this, how can I create Json string properly?
Edit : Is there a chance of making a mistake while rendering the myjson?
Edit2: To reach the result of myjson in view, i'm doing
render(myjson);
at the end of my code.
Edit3: Play framework has a method of renderJSON(). However i can't use it since i'm rendering not only myjson and some other elements too.
Note that "&quot" is "Proper" JSON, so your javascript can be escaped properly, anyways if you dont want to use entities in you JSON perhaps you want to disable html formatting/escaping.
Try using
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
Check the GSONBuilder Object Documentation http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/GsonBuilder.html
I think he's protecting you against html special chars.
Try something like that:
Gson gson = new Gson();
String target = "my text";
String json = gson.toJson(target);
This code is extract from http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html (the api).

Create JSON object and convert it to String in Java

I need to send a quite long JSON header through an http post. In Python was like this:
self.body_header = {
"client": self.client_name,
"clientRevision": self.client_version,
"uuid": str(uuid.uuid4()),
"session": self.get_sessionid()}
self.body = {
"header": self.body_header,
"country": {"IPR":"1021", "ID":"223", "CC1":"0", "CC2":"0", "CC3":"0", "CC4":"2147483648"},
"privacy": 1}
I need to do something similar in Java, ie, create somehow a JSON struct, convert it to a String and send it via http.
The question is, how can I achieve that easily? Any useful libraries? I know how to send it, but not how to build it and then create a String.
Thank you all.
You can use gson.
You can create a Java Object (POJO) and serialize it as JSON by doing:
Gson gson = new Gson();
String json = gson.toJson(yourObject);
You can then send the string over HTTP.
If you do not want to go the POJO route, you can still create the JSON struct using JsonElement, JsonArray, JsonObject in the Gson API.
I like the original org.json
i think STO had a similar discussion https://stackoverflow.com/questions/338586/a-better-java-json-library

Categories