我需要将json的ajax请求传递给我的休息服务。 我的模型类是
@Entity
@Table(name = "messageslist")
public class MessageList {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer id;
public String title;
public String tags;
public String documents;
public String links;
//Then getters and setters
}
休息控制器
@RequestMapping(value = "/AddPost", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<MessageList> addPost(@RequestBody @Valid MessageList messageList, BindingResult bindingResult,
UriComponentsBuilder ucBuilder) {
BindingErrorsResponse errors = new BindingErrorsResponse();
HttpHeaders headers = new HttpHeaders();
if (bindingResult.hasErrors() || (messageList == null)) {
errors.addAllErrors(bindingResult);
headers.add("errors", errors.toJSON());
return new ResponseEntity<MessageList>(headers, HttpStatus.BAD_REQUEST);
}
this.taskManagerService.savePost(messageList);
headers.setLocation(ucBuilder.path("/api/TS/{id}").buildAndExpand(messageList.getId()).toUri());
return new ResponseEntity<MessageList>(messageList, headers, HttpStatus.CREATED);
}
从客户端代码
var post = JSON.stringify({
title : title,
tags : tags,
documents : documents,
links : links
});
var url = "http://localhost:8080/TS/AddPost";
$.ajax({
type : 'POST',
url : url,
contentType : 'application/json; charset=utf-8',
data : post,
dataType : 'json',
success : function(data) {
onComplete();
}
});
我从ajax调用传递的json数据就像
{"title":"dhfg","tags":["Interactive","Online"],"documents":[],"links":[]}
如何从json传递tags数组?我是Java新手
错误详情
2017-09-24 01:40:31.978 WARN 9600 --- [nio-8081-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize instance of java.lang.String out of START_ARRAY token
at [Source: java.io.PushbackInputStream@459b29e9; line: 1, column: 24] (through reference chain: org.fs.spring.tm.model.MessageList["tags"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_ARRAY token
at [Source: java.io.PushbackInputStream@459b29e9; line: 1, column: 24] (through reference chain: org.fs.spring.tm.model.MessageList["tags"])
答案 0 :(得分:0)
我从
更改了模型类中标签的数据类型public String tags;
到
public ArrayList<String> tags;
解决了我的问题:)