我在这里尝试将JSON值绑定到带有RequestBody的java模型中,但它不会绑定到我的java模型中。这是我的代码:
这是我的HelloController.java
@RequestMapping(value = "/transaksi/", method = RequestMethod.POST)
public ResponseEntity<Void> simpanKupon(@RequestBody TransaksiKupon transaksi, UriComponentsBuilder ucBuilder) {
String a = "asdf";
/* if (userService.isUserExist(user)) {
System.out.println("A User with name " + user.getNM_TOKO() + " already exist");
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}*/
transaksiService.saveKupon(transaksi);
HttpHeaders headers = new HttpHeaders();
/*headers.setLocation(ucBuilder.path("/login").buildAndExpand(transaksi.getKodevoucher()).toUri());*/
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
我使用POST作为请求方法,但它不起作用,&#34; transaksi&#34; model为null
但是当我使用GET作为请求方法时,它可以正常工作。这是我在另一个控制器中的代码:
@RequestMapping(value = "/transaksi/{KODEVOUCHER}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<TransaksiKupon> getValidasi(@PathVariable("KODEVOUCHER") String KODEVOUCHER) {
TransaksiKupon trxKupon = transaksiService.validasi(KODEVOUCHER);
if (trxKupon.getKODEVOUCHER() != null){
return new ResponseEntity<TransaksiKupon>(HttpStatus.NOT_FOUND);
}
/*if (trxkupon == null) {
System.out.println("User with id " + KODEVOUCHER + " not found");
return new ResponseEntity<TransaksiKupon>(HttpStatus.NOT_FOUND);
}*/
return new ResponseEntity<TransaksiKupon>(trxKupon,HttpStatus.OK);
}
它只是正常工作。这是我提交表单时的angularjs代码,app.js:
'use strict';
App2.factory('KuponService', ['$http', '$q', function($http, $q){
return {
simpanKupon: function(transaksi){
alert(JSON.stringify(transaksi));
return $http.post('http://localhost:8080/webbass/transaksi/', transaksi)
.then(
function(response){
return response.data;
},
function(errResponse){
console.error('Error while save transaksi');
return $q.reject(errResponse);
}
);
},
validasiKupon: function(transaksi){
/*var KODEVOUCHER = transaksi.KODEVOUCHER;*/
return $http.get('http://localhost:8080/webbass/transaksi/'+transaksi)
.then(
function(response){
return response.data;
},
function(errResponse){
console.error('Tidak ada Nomor Kupon ini');
return $q.reject(errResponse);
}
);
}
};
}]);
这是我的依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1.3</version>
</dependency>
我错过了什么?我被困了差不多一个星期,帮助我!
答案 0 :(得分:0)
在这种情况下你依赖你的解析器 - 杰克逊,但你必须用Jackson Annotstions注释你的身体对象,或者在application.yml中为app配置解析器,如果你使用Spring Boot,它将按字段名解析。