从@ResponseBody创建JsonObject

时间:2012-11-24 11:56:01

标签: json spring spring-mvc

@RequestMapping(value = "/dropDown", method = RequestMethod.GET)
public @ResponseBody
DropDown getList(Map<String, Object> map, HttpServletRequest request,
        HttpServletResponse response) {
    DropDown dropDown = new DropDown();
    List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
    List<MapTable2> list = contactService.mapProcess();
    for (MapTable2 table : list) {
        Map<String, Object> dataRow = new HashMap<String, Object>(1);
        dataRow.put("text", table.getProcess());
        dataRow.put("value", table.getId());
        dataRow.put("selected", false);
        dataRow.put("description", table.getProcess());
        dataRow.put("imageSrc", "image.jpg");
        rows.add(dataRow);
    }
    dropDown.setRows(rows);
    return dropDown;
}

我需要创建以下一个

var ddData = [
{
    text: "Facebook",
    value: 1,
    selected: false,
    description: "Description with Facebook",
    imageSrc: "http://dl.dropbox.com/u/40036711/Images/facebook-icon-32.png"
},
{
    text: "Twitter",
    value: 2,
    selected: false,
    description: "Description with Twitter",
    imageSrc: "http://dl.dropbox.com/u/40036711/Images/twitter-icon-32.png"
}]

我知道上面java编码的问题,我不知道如上所述创建json数组。 请检查并帮我纠正。

MapTable2有ProcessId&amp; ProcessName

public class MapTable2 {
private int id;
private String process;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getProcess() {
    return process;
}
public void setProcess(String process) {
    this.process = process;
}

}

2 个答案:

答案 0 :(得分:3)

@theon是对的。

由于您使用的是@Responsebody,因此您可以让Spring为您执行JSON转换。创建一个与JSON数组中的对象匹配的类:

public class SomeObject {
    public String getText() { //... }
    public int getValue() { //... }
    public boolean getSelected { // ... }
    public String getDescription { // ... }
    public String getImageSrc { // ... }
}

填充对象并将其作为控制器列表返回:

@RequestMapping(value = "/dropDown", method = RequestMethod.GET)
@ResponseBody
public List<SomeObject> getList(Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) {
     // Get the objects, return them in a list
}

Add <mvc:annotation-driven />@EnableWebMvc到你的应用程序配置,除非你还没有这样做。确保Jackson在类路径中可用,然后Spring会自动将对象序列化为JSON(如果请求有Content-Type: application/json。或者,可以将produces属性添加到@RequestMapping注释中总是返回JSON)。

答案 1 :(得分:1)

好吧使用这个library。它重量很轻(16KB),可以满足您的需求。 因此,在您的情况下,您将使用内部扩展JSONObject的{​​{1}} 并做

HashMap

以上内容将为您提供:

JSONObject o = new JSONObject();
o.put("text","whatever text");
o.put("value",1);
o.put("selected",false);
//and so on
JSONArray arr = new JSONArray();
arr.add(o);

要添加更多对象,请在循环中向[ { text: "Facebook", value: 1, selected: false, description: "Description with Facebook", imageSrc: "http://dl.dropbox.com/u/40036711/Images/facebook-icon-32.png" } ]

添加更多JSONObjects

根据您给定的代码,只需将JSONArray替换为'JSONObject',将dataRow替换为rows就可以了。最后,要检索字符串,请执行JSONArray