Convert string to JsonObject | Community
Skip to main content
New Participant
June 13, 2023
Solved

Convert string to JsonObject

  • June 13, 2023
  • 3 replies
  • 5712 views

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?

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by Rohan_Garg

@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

3 replies

Ritesh_Mittal
New Participant
June 13, 2023

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!

Rohan_Garg
Rohan_GargAccepted solution
New Participant
June 13, 2023

@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

New Participant
June 13, 2023

Thank you @roh 

aanchal-sikka
New Participant
June 13, 2023

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