简体   繁体   English

POJO对象到Java中的JSON对象转换

[英]POJO object to JSON Object conversion in java

My requirement is needed to convert POJO OR DTO Object into JSON Format, I have used below methodology 我需要将POJO或DTO对象转换为JSON格式,我使用了以下方法

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. 但是与此同时,我将关键数据作为字符串获取(例如:“ employee”),因此,如果我将此数据插入数据库,则仅使用双引号(“ employee”)进行插入。

You can do it easily by using third party libraries like Jackson or Gson to serialize and deserialize objects. 您可以通过使用第三方库(例如JacksonGson)对对象进行序列化和反序列化来轻松实现。

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 Gson:参考代码段

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. 但是似乎这里的主要问题是您在将序列化数据插入DB并解决您需要提供有关该问题的更多信息时遇到了问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM