简体   繁体   中英

convert json to pojo using jquery/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);
  }
});

and the controller is :

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

The output I get in dialog shows this :

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

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

Whilst my sys out console output shows both fields are null, the json has not bound !!! Why ? The DTO itself just has two private fields with appropriate getters/setters

//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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM