将数组列表转换为json对象字符串

我有一个模型类方法,它返回一个包含所有注册用户详细信息的对象列表。 我想获取all()方法重新定义的列表,并将数据转换为JSON对象,并将其作为字符串传递给视图。 如何将此数组列表转换为JSON对象?

我无法通过以下方式执行此操作:

ObjectMapper mapper = new ObjectMapper(); JSONObject json = new JSONObject(); JsonNodeFactory jsonnode = JsonNodeFactory.instance; ObjectNode result = new ObjectNode(jsonnode); for (int i = 0; i < list.size(); i++) { json.put(list.get(i).fname, list.get(i)); System.out.println(json.get("fname")); } @Entity class Mydata extends Model { @Id public Long Id; public String fname; public String lname; public String city; public String state; /****************** READ/select OPERATION *****************/ public static Finder  finder = new Finder(Long.class, Mydata.class); public static List  all() { return finder.all(); } public static void createuser(Mydata user) { user.save(); } } 

要将ArrayList转换为Json,只需从以下url下载开源json实用程序: http : //json.org/java/或Jar文件

而且只是做:

 JSONArray jsonAraay = new JSONArray(your_array_list); 

而已

注意:您应该在POJO / MODEL类中使用setter / getter将arraylist转换为json

不要打扰org.json,一直使用Jackson:

 // list is a List final ObjectMapper mapper = new ObjectMapper(); final Map map = new HashMap<>(); for (final MyData data: list) map.put(data.fname, data); final JsonNode json = mapper.valueToTree(map); 

您可以像其他人建议的那样使用各种第三方库,或者只使用Play自己的简化方法(在play.libs.Json找到)与Jackson对象一起使用,但它被集成到框架中并需要很多减少使用的代码,例如:

JsonNode myJsonNode = Json.toJson(MyListObject); 它将List转换为JsonNode对象,然后使用String jsonResult = Json.stringify(myJsonNode); 将其转换为字符串表示forms。

如果您在模板中使用JSON,请不要忘记将其包装在@Html(myJsonString)这样它就不会逃避任何事情。 否则,如果您只是将纯JSON输出到浏览器,则return ok(jsonResult);一个简单的return ok(jsonResult); Play将自动设置内容类型。

参考链接: http : //www.playframework.com/documentation/api/2.0/java/play/libs/Json.html

你看过这个: http : //www.json.org/javadoc/org/json/JSONObject.html#valueToString(java.lang.Object)

 JSONObject.valueToString(<> OR <> OR <>) 

工作得很好……如果你感兴趣的话,那个lib上还有其他一些方法……