简体   繁体   English

如何轻松将POJO转换为JSON数据?

[英]How can I easily convert my POJO's into JSON data?

How can I make this more reusable across our DAO objects? 如何使它在我们的DAO对象中更可重用?

List<User> list = userService.getAll();

JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();

for(User user : list) {
    JSONObject userJson = new JSONObject();
    userJson.put("id", user.getId());
    userJson.put("FirstName", user.getFirstName());
    ....
    jsonArray.add(userJson);
}

json.put("results", jsonArray);

return json.toJsonString();

Anyway, that's code from memory but you get the idea. 无论如何,这是内存中的代码,但是您可以理解。 There has to be an easier way. 必须有一种更简单的方法。 Also, we don't always want to return every property of the POJO. 另外,我们并不总是希望返回POJO的每个属性。 In some situations, we may only want the FirstName and LastName and in others, we would add PhoneNumber , etc. 在某些情况下,我们可能只需要FirstNameLastName而在其他情况下,我们将添加PhoneNumber等。

Thanks for any suggestions. 感谢您的任何建议。

I would use Google Gson 我会用Google Gson
Very easy to use 很好用

You can also try Genson library http://code.google.com/p/genson/ . 您也可以尝试Genson库http://code.google.com/p/genson/

It has full databinding support but also a low level streaming api. 它具有完整的数据绑定支持,但还具有低级别的流API。 It is easy to use, according to users feedback it would be easier to use than Jackson. 它易于使用,根据用户反馈,它将比Jackson更易于使用。 There are a couple of features that it is the only one to provide, such as deserialization to an object using its constructor with any additional annotations. 有几个特征,这是唯一的一个,以提供,例如反序列化使用它的构造与任何附加的注释的对象。

To get started you can have a look at the wiki http://code.google.com/p/genson/wiki/GettingStarted it should help to start quickly. 要开始,你可以看看维基http://code.google.com/p/genson/wiki/GettingStarted应该有助于快速启动。

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

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