over 3 years ago

要讓Spring自動幫你轉成Json格式有很多方法,目前採用Jackson2解決方式

1.首先必須匯入幾個jar檔

  • jackson-annotations-2.2.0.jar
  • jackson-core-2.2.0.jar
  • jackson-databind-2.2.0.jar

2.接著在Spring設定檔中必須聲明你的轉接器 如下

spring-servlet.xml
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="cacheSeconds" value="0" />
    <property name="messageConverters">
        <list>
            <bean
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
        </list>
    </property>
</bean>

3.在Controller中可利用HashMap作為回傳物件,透過Spring自動轉換,記得加註解@ResponseBody

BankController.java
@ResponseBody
@SuppressWarnings("finally")
@RequestMapping(value="create",method=RequestMethod.POST)
public Map create(
        @ModelAttribute("bank")Bank bank,
        BindingResult result
        ){
    Map<String, Object> map = new HashMap<String, Object>();
    try {
        this.validator.validate(bank, result);
        if (result.hasErrors()){
            map.put("prc", "0");
            map.put("msg", "建檔失敗");
            map.put("errorlist", CommonTool.BindingResultToList(result));
        }else{
            bankservice.create(bank);
            map.put("prc", "1");
            map.put("msg", "建檔成功");
        }
    } catch (Exception e) {
        log.error("建檔失敗(系統異常)", e);
        map = new HashMap<String, Object>();
        map.put("prc", "0");
        map.put("msg", "建檔失敗(系統異常)");
    } finally{
        return map;
    }
}

4.得到回覆結果如下

{"prc":"1","msg":"建檔成功"}
除錯小筆記 →
 
comments powered by Disqus