Yevhen
Yevhen

Reputation: 801

AWS Lambda Java return string with slashes

I have problem with returning string from Lambda after

JSONObject.toString

in return i have

"{\"Key2\":\"Value2\",\"Key1\":\"Value1\"}" 

instead of

"{"Key2":"Value2","Key1":"Value1"}"

Can somebody explain how to exclude these slashes?

Upvotes: 6

Views: 3586

Answers (3)

Tatenda Zifudzi
Tatenda Zifudzi

Reputation: 661

Don't serialize your object in your project. AWS Lambda will handle object serialization for you as mentioned here. Just return an object!

e.g.

//return type is an object not a string
public SomeObject handleRequest(Object input, Context context) {
...
}

Upvotes: 1

Chris
Chris

Reputation: 3338

I've done similar to this before in JavaScript. If you don't serialize the object at all, then AWS API Gateway should take care of it for you. If your Lambda returns something like this:

// ...
context.done(null, {
    id: i.id,
    last_name: i.last_name,
    gender: i.gender
});

...then your API response will look something like this:

{
    "id": 1,
    "first_name": "Chris",
    "gender": "male"
}

Upvotes: 0

Yassine Badache
Yassine Badache

Reputation: 1851

If you really need to remove them ...

yourstring.replace("\\", "");

However, those "stupid slashes" are necessary if you are treating your response as a string, as they escape your " character. Specifically, without those, your compiler would behave as such:

"{"     // is a string
Key2    // Not known by Java
":"     // is a string
Value2  // Not known by Java
","     // is a string
Key1    // Not known by Java
":"     // is a string
Value1  // Not known by Java
"}"     // is a string

By escaping your " character with a backslash, you are mentionning to your compiler that it should not be taken as an end of string nor a begin. Thus, asking it to only take in account the first and last ".

Upvotes: 1

Related Questions