使用jquery / spring / jackson将json转换为pojo

时间:2012-02-29 11:21:53

标签: java json spring jackson

$.ajax({
  cache:false,
  type: 'POST',
  url: "${saveDTO}",
  data: mySubmitData, //a stringified json object, a form converted using toObject plugin
  contentType: "application/json",
  success:  function(data) {            
    savedDialog.html( JSON.stringify(data) + "<br><br>"+mySubmitData);
  }
});

,控制器是:

public @ResponseBody MyDTO saveDTO(@Valid final MyDTO myDTO,BindingResult result, Model model){
 System.out.println(myDTO.getMyField + "  " + myDTO.getSecondField;
 return new MyDTO();
}

我在对话框中输出的输出显示:

{"myField":null,"secondField":null} //new empty dto converted and returned spring

{"myField":"RU","secondField":"13-02-12"} //submitted data, a form converted to json

虽然我的sys out控制台输出显示两个字段都为null,但是json没有绑定!为什么? DTO本身只有两个私有字段和适当的getter / setter

1 个答案:

答案 0 :(得分:0)

//js
var mySubmitData ='{"myField":"myFieldValue", "secondField":"secondFieldValue"}';
//dto
public class MyDTO implements Serializable {

  private String myField;

  private String secondField;

  MyDTO() {} //important

  public void setMyField() { ...}

  public void setSecondField() { ... }
}
//web resource
    public @ResponseBody MyDTO saveDTO(@Valid final MyDTO myDTO,BindingResult result, Model model){
     System.out.println(myDTO.getMyField + "  " + myDTO.getSecondField;
      return  myDTO;
      //return new MyDTO(); //it's empy object if you don't have default values
    }