5

My requirement is needed to convert POJO OR DTO Object into JSON Format, I have used below methodology

JsonObject obj = gson.toJsonTree(pojo class).getAsJsonObject();
for (String key: obj.keySet()) {
    System.out.println(" key is " + key + " value  is " + obj.get(key));
}

But with this i am getting key data as string(eg:"employee"), so if i insert this data in database it inserting with double quotes("employee") only.

2
  • So the problem is not with json conversion but with storing it in the database? Commented Jan 9, 2019 at 13:50
  • yes, it is storing in database as string,JsonObject obj= new JsonObject(gson.toJson(object_need)) by looping obj i am getting proper data. by using this code by problem resolved Commented Jan 9, 2019 at 16:56

1 Answer 1

6

You can do it easily by using third party libraries like Jackson or Gson to serialize and deserialize objects.

Jackson: Reference code snippet:

ObjectMapper mapper = new ObjectMapper();
User user = new User();

//Object to JSON in file
mapper.writeValue(new File("c:\\user.json"), user);

//Object to JSON in String
String jsonInString = mapper.writeValueAsString(user);

You can find detailed info from here

Gson: Reference code snippet

User user = new User();
Gson gson = new Gson();

// Object to JSON in String
String json = gson.toJson(object_need);

For detailed usages as reference:

But it seems like the main problem here is you have a problem at inserting the serialized data to DB and to solve that you need to give more information about the issue.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your update , is there anyway by using gson library,instead of jackson library because ,in my project don't have jackson library for this single requirement i can't add jackson jar file in my project.
I answered regarding to title of the question. Since there is no information given about the issue for storing data on DB, I editted my answer to request more information from the OP

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.