Vaishak Suresh
Vaishak Suresh

Reputation: 5845

What is a good way to convert a valid or invalid JSON to a string?

I have a service that gets JSON inputs, but occasionally also gets invalid JSON contents. I don't have control over this behavior. The input can be

{"key":{"k1":"v1"},"key2":"value2"}

or

{"key":{"k1":"v1"},"Random String"}

My idea is to wrap this whole thing into a valid JSON as below

{"id":"some id", "raw_data":"the above input as string"}

I know I can escape all quotes and treat it like a string, but is there a cleaner way to convert JSON to escaped string?

FWIW, I'm using Jackson for parsing and processing.

EDIT: The JSON schema isn't clear upfront and can vary with different inputs.

Upvotes: 0

Views: 94

Answers (1)

Adam Siemion
Adam Siemion

Reputation: 16039

I know I can escape all quotes and treat it like a string, but is there a cleaner way to convert JSON to escaped string?

Just create a class with the raw_data attribute, set this attribute with the JSON you have received (correct or incorrect) and let Jackson serialise it (and take care of making it a correct JSON).

Upvotes: 1

Related Questions