2014-02-21 156 views
1

我目前正在将REST webservices实现到现有系统中。该系统在版本2中使用Spring(特别是2.5.6.SEC02)。我无法将其升级到版本3,因为它可能会破坏现有的系统组件。我们没有制造这个系统的其余部分,没有源代码,也不想失去保修,所以春天的版本应该基本上保持原样:)Spring MVC中的ResponseBody 2

问题是,我该如何实施Rest WS自动DTO序列化从/到JSON?我在classpath上有适当的Jackson库。 Spring 2似乎还不了解@RequestBody和@ResponseBody。有没有其他可以使用的注释,或其他方式?

回答

2

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

https://github.com/FasterXML/jackson

首先,接受JSON字符串作为从请求中的参数,然后手动分析字符串和从使用杰克逊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

您可以尝试使用Spring MVC控制器的DIY方法,以及json.org的JSONObject。只需使用它来对返回的对象进行json序列化,并使用适当的头文件将其刷新到响应中即可。

它有它的缺陷(我建议你在尝试发送一个集合时使用一个简单的包装类与getter),但我一直对它满意的一些年。

相关问题