简体   繁体   中英

Convert java bean to json string using Struts

I want to use struts to render content in a JSP page.

I have the Java Bean class implementing Serializable :

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:

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.

On the jsp page I use:

<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:

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? 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?

Because you didn't override ArrayList toString() method. Your property is a collection that has to be serialied to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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