Expand my Community achievements bar.

SOLVED

Convert string to JsonObject

Avatar

Level 5

I'm writing a servlet where we are getting a response from a third party API. The response we are getting is in String format, something like - {_ "errors" : [ {_ "message" : "Language encurr=USD is not supported",_ "type" : "UnsupportedLanguageError"_ } ]_}

 

I need to store this in JsonObject format so that we can access the keys properly. 

JsonObject json = new JsonObject(restServiceResponse.getResponseString()); is throwing error.

 

How can this be attained?

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

@goyalkritika - You can use GSON library's fromJson to deserializes the Json read from the specified parse tree into an object of the specified type.

Gson gson = new Gson();
JsonObject json = gson.fromJson( restServiceResponse.getResponseString(), JsonObject.class);

 

Refer the below URL for documentation -https://www.javadoc.io/doc/com.google.code.gson/gson/2.8.5/com/google/gson/Gson.html

View solution in original post

4 Replies

Avatar

Community Advisor

hello @goyalkritika 

 

In case you are getting an error message, please validate if Json is valid like on

https://jsonlint.com/ 

What is the '_' in the json that you have shared? If the json is valid, may be split the json into smaller chunks and check, if any specific key/value has issue during conversion to JsonObject

 

Also, you might want to convert them to Beans. It just becomes easier to understand and access the structure.

https://www.tutorialspoint.com/how-to-convert-a-json-string-to-a-bean-using-json-lib-api-in-java


Aanchal Sikka

Avatar

Correct answer by
Community Advisor

@goyalkritika - You can use GSON library's fromJson to deserializes the Json read from the specified parse tree into an object of the specified type.

Gson gson = new Gson();
JsonObject json = gson.fromJson( restServiceResponse.getResponseString(), JsonObject.class);

 

Refer the below URL for documentation -https://www.javadoc.io/doc/com.google.code.gson/gson/2.8.5/com/google/gson/Gson.html

Avatar

Community Advisor

Hi @goyalkritika ,

 

If I have understood the question correctly then-

 

1. You have an external API to be consumed which provides response as String.

2. You have written custom Sling Servlet where you want to convert this response to JSON Object.

3. You want to read objects from the JSON object converted in step#2.

 

for this you can simply set content type as application/json

 

String apiResponse = //Caling external API

PrintWriter out = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(apiResponse)

 

 

Hope it helps!