Reputation: 443
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.
Upvotes: 5
Views: 7111
Reputation: 6872
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.
Upvotes: 6