2016-11-07 21 views
2

私はRESTサービスをトライニングしていますが、今では新しいアイテムを追加しようとしています。START_ARRAYトークンのうちmodel。*のインスタンスを逆シリアル化できません

モデルメッセージ:

@Entity 
@Table(name="message") 
public class Message{ 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    @Column(name = "ID") 
    private long id; 
    @Column(name = "MESSAGE") 
    private String message; 
    @Column(name = "AUTHOR") 
    private String author; 
    @Column(name = "CREATED") 
    @Temporal(TemporalType.DATE) 
    private Date created; 

    public Message() {} 

    public Message(Long id, String message, String author) { 
     this.id = id; 
     this.message = message; 
     this.author = author; 
     this.created = new Date(); 
    } 
+ getters/setters 

MessageController:

@RestController 
public class MessageController { 

    @Autowired 
    private MessageRepository messageRepository; 

    @RequestMapping(
     value = "/api/messages", 
     method = RequestMethod.POST, 
     consumes = MediaType.APPLICATION_JSON_VALUE, 
     produces = MediaType.APPLICATION_JSON_VALUE) 
    public ResponseEntity<?> addMessage(@RequestBody Message newMessage) { 
     return new ResponseEntity<>(messageRepository.save(newMessage), HttpStatus.CREATED); 
    } 
} 

エラー:

2016-11-06 10:52:53.857 WARN 1100 --- [nio-8080-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 com.sttech.springrest.model.Message out of START_ARRAY token at [Source: [email protected]; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.sttech.springrest.model.Message out of START_ARRAY token at [Source: [email protected]; line: 1, column: 1]

ポストマンを通して、私はJSONに新しいデータを送信し、ポストマンの答えを得る

[ 
    { 
    "message": "Hello World1", 
    "author": "ABC" 
    } 
] 

"exception": "org.springframework.http.converter.HttpMessageNotReadableException", "message": "Could not read document: Can not deserialize instance of com.sttech.springrest.model.Message out of START_ARRAY token\n at [Source: [email protected]; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.sttech.springrest.model.Message out of START_ARRAY token\n at [Source: [email protected]; line: 1, column: 1]"

どのように修正するのですか?私はモデルがidを取得しないと思う。

答えて

2

サービスでは、1つのメッセージが必要です。ただし、メッセージの配列を送信します(メッセージは1つだけです)。

ので、代わりの:

[ 
    { 
    "message": "Hello World1", 
    "author": "ABC" 
    } 
] 

はあなただけ送信する必要があります:

{ 
    "message": "Hello World1", 
    "author": "ABC" 
} 
+0

私は配列を送信することができますどのように? –

+0

JSON配列を処理するにはどうすればいいですか? APIの署名を 'public ResponseEntity addMessage(@RequestBody List newMessages)'に変更してから、メッセージのリストを処理する必要があります。 – Codo

関連する問題