Spring MVC 2中的ResponseBody

时间:2014-02-21 09:05:15

标签: java json spring rest spring-mvc

我目前正致力于在现有系统中实施REST Web服务。该系统在版本2中使用Spring(特别是2.5.6.SEC02)。我无法将其升级到版本3,因为它可能会破坏现有的系统组件。我们没有制作本系统的其余部分,没有源代码而且不想失去保修,因此Spring版本应该基本保持不变:)

问题是,我如何使用自动DTO序列化从/到JSON实现Rest WS?我在类路径上有适当的杰克逊库。 Spring 2似乎还不了解@RequestBody和@ResponseBody。是否有其他可以使用的注释或其他替代方法?

2 个答案:

答案 0 :(得分:2)

您可能需要手动解析JSON字符串并将其写入响应,以便为您工作。我建议使用jackson2 API。

https://github.com/FasterXML/jackson

首先,接受一个json String作为请求中的参数,然后使用jackson ObjectMapper手动将字符串解析为POJO。

这是jQuery / JavaScript:

function incrementAge(){

    var person = {name:"Hubert",age:32};

    $.ajax({

        dataType: "json",
        url: "/myapp/MyAction",
        type: "POST",
        data: {
            person: JSON.stringify(person)
        }

    })
    .done(function (response, textStatus, jqXHR) {

        alert(response.name);//Hubert
        alert(response.age);//33
        //Do stuff here
    });
}

人物pojo:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

//Allows name or age to be null or empty, which I like to do to make things easier on the JavaScript side
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person{

    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

这是控制器:

import com.fasterxml.jackson.databind.ObjectMapper;

/*snip*/

@Controller
public class MyController{

    //I prefer to have a single instance of the mapper and then inject it using Spring autowiring
    private ObjectMapper mapper;

    @Autowired
    public MyController(ObjectMapper objectMapper){

        this.objectMapper = objectMapper;
    }

    @RequestMapping(value="/myapp/MyAction", method= {RequestMethod.POST})
    public void myAction(@RequestParam(value = "person") String json, 
                         HttpServletResponse response) throws IOException {

        Person pojo = objectMapper.readValue(new StringReader(json), Person.class);

        int age = pojo.getAge();
        age++;
        pojo.setAge(age);

        objectMapper.writeValue(response.getOutputStream(),pojo);
    }
}

答案 1 :(得分:1)

您可以尝试使用Spring MVC控制器的DIY方法和来自json.org的JSONObject。只需使用它来json序列化您返回的对象并使用适当的标题将其清除响应。

它有它的缺陷(我建议你在尝试发送一个集合时使用一个带有getter的简单包装器类),但我已经很满意它了几年。