简体   繁体   English

使用Struts将Java bean转换为json字符串

[英]Convert java bean to json string using Struts

I want to use struts to render content in a JSP page. 我想使用Struts在JSP页面中呈现内容。

I have the Java Bean class implementing Serializable : 我有实现Serializable的Java Bean类:

public class MyPOJO implements Serializable {
    String name;
    int value;
    // A lot of other members, but all String or int
    // Getters and setters
}

And my form class with a list of MyPOJO: 我的表单类带有MyPOJO列表:

public class MyForm extends ActionForm {
    private List<MyPOJO> results = new ArrayList<MyPOJO>();
    // Getter and setter
}

And a class inheriting DispatchAction to pass a MyForm object onto the page. 还有一个继承DispatchAction的类,以将MyForm对象传递到页面上。

On the jsp page I use: 在jsp页面上,我使用:

<logic:notEmpty name="myForm" property="results">
var jsonData = ${myForm.results};
</logic:notEmpty>

The final result in the generated jsp file is a list of MyPOJO objects: 生成的jsp文件中的最终结果是MyPOJO对象的列表:

var jsonData = [com.package.MyPOJO@174aee5, ...] var jsonData = [com.package.MyPOJO@174aee5,...]

I'd like to know, without overriding toString() method inside MyPOJO class is there any other way to directly convert it to json String? 我想知道,在不重写MyPOJO类内部的toString()方法的情况下,还有其他方法可以将其直接转换为json String吗? I've also created a rest service returning a list of MyPOJO, without the toString() method, it can already show the JSON string, I'd like to know why it doesn't work for the JSP form bean? 我还创建了一个rest服务,该服务返回一个MyPOJO列表,没有toString()方法,它已经可以显示JSON字符串,我想知道为什么它不适用于JSP form bean?

Because you didn't override ArrayList toString() method. 因为您没有重写ArrayList toString()方法。 Your property is a collection that has to be serialied to JSON. 您的属性是一个必须序列化为JSON的集合。 You could either extend ArrayList and override that method or use natively JSONArray or JSONObject toString() that is already overridden and returns a JSON string. 您可以扩展ArrayList并覆盖该方法,也可以使用已被覆盖并返回JSON字符串的本机JSONArrayJSONObject toString()

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

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