larsien larsien - 1 month ago 15
Node.js Question

How to convert data from AWS lambda node.js to JSONObject in Java

My code snippet of lambda is

dynamodb.query( params
, function(err, data) {
if (err) {
context.done(err);
}
else {
console.log(JSON.stringify(data)); // successful response
var size = data.Items.length;
console.log("size:"+ size);
var rand = Math.floor(Math.random() * (size));
console.log("rand" + rand);
var ret = data.Items[rand].content;
console.log(ret);
context.succeed(JSON.stringify(ret));
}


My AWS Lambda log of ("console.log(JSON.stringify(data)); // successful response") is

{"Items":[{"content":{"S":"content1"}},{"content":{"S":"content2"}}],"Count":2,"ScannedCount":2}


And result of "JSON.stringify(ret)" is

{"S":"content1"}


In my Android code, call this API and just show the result.
But it only showed "java.lang.String cannot be converted to JSONObject"

I wonder how to convert to JSONObject in Android.

I used this code in Android

new JSONObject(notice).getJSONObject("S");

Answer

The problem is you are calling getJSONObject. The object you are getting is a String.

{"S":"content1"}
^JSON    ^String

You should be calling get

JSONObject jsonNotice = new JSONObject("{\"S\":\"hello, world\"}");
String contentsOfS = jsonNotice.get("S");

The method getJSONObject is for nested JSON objects:

{"S": {"foo": "bar"}}
^JSON ^JSON
Comments