【发布时间】:2018-05-17 01:07:07
【问题描述】:
首先,我对 spring (web mvc) 很陌生。我正在为我的前端构建一个 RESTful 服务。我正在发送一个 JSON 数据,但该数据中的一个对象在 spring 接收时没有被解析。
这是我的数据
JSON 数据
{
"comments" : []
"description": "Testing",
"images": "[\"path1\", \"path2\", \"path3\"]",
"profile": {
"id": 21234,
"fullname": "John Michael Doe",
"nickname": "Doe",
"email": "jdoe@email.com",
"profilePic": "/some/host/pic"
}
}
RequestMapper
@RestController
@RequestMapping("/wish")
public class WishlistController extends WishlistConverter{
/* Some @Autowired here for services... */
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> create(@RequestBody RestWishlist input){
try {
logger.info("create({})",input);
Wishlist wish = convert(input);
wishlistService.create(wish);
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception e) {
logger.error("Error: {}",e.getMessage());
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
}
RestWishlist
public class RestWishlist {
private Long wishId;
private List<RestComment> comments;
private String description;
private String images;
private Long createdAt;
private Long updatedAt;
private RestProfile profile;
/* Getters and Setters here */
}
RestProfile
public class RestProfile {
private Long id;
private String fullname;
private String nickname;
private String email;
private String profilePic;
/* Getters and Setters Here */
}
RestComment
public class RestComment {
private Long commentId;
private String description;
private RestProfile profile;
private Long createdAt;
private Long updatedAt;
/* Getters and Setters Here */
}
现在,我在获取 JSON 数据的“配置文件”部分时遇到问题,日志文件显示此内容
2017-12-03 20:50:31.740 INFO 10212 --- [nio-8080-exec-1] c.s.s.web.controller.WishlistController : create(RestWishlist [wishId=null, comments=[], description=Testing, images=["path1", "path2", "path3"], createAt=null, updatedAt=null])
2017-12-03 20:50:31.740 INFO 10212 --- [nio-8080-exec-1] c.s.s.services.impl.WishlistServiceImpl : create(Wishlist [wishId=null, comments=[], description=Testing, images=["path1", "path2", "path3"], createAt=null, updatedAt=null])
【问题讨论】:
-
从服务配置文件对象发送数据时没有收到是吗?
-
如果配置文件属性的值为空,那么它可能会从生成的 JSON 中被跳过。
-
@swapnil - 基于我发送给 spring 的 JSON 数据,“profile”具有价值,请查看我的 JSON 数据。
-
尝试“@ModelAttribute”而不是“@RequestBody”。
-
尝试使用 @ModelAttribute 但我的 JSON 数据中的所有字段在 spring 收到后都变为空。
标签: java spring spring-mvc spring-boot jackson