2017-01-10 3 views
1

스프링 부트 프로젝트에서 json을 읽으려고합니다.springboot deserialize 할 수 없습니다 -HttpMessageNotReadableException

[{ 
    "userId":"101" 
}, 
{ 
    "partNum":"aaa" 
}, 
{ 
    "partNum":"bbb" 
}, 
{ 
    "partNum":"ccc" 
}] 

나는 DTO 클래스를 만들었습니다 :

public class TcPartDto { 
    private String userId; 
    private List<String> partNum; 

    public String getUserId() { 
     return userId; 
    } 
    public void setUserId(String userId) { 
     this.userId = userId; 
    } 
    public List<String> getPartNum() { 
     return partNum; 
    } 
} 

를 다음과 같이 내 컨트롤러에 호출하고 다음과 같이

내 JSON 데이터는

@RequestMapping(value = "/volumeinfo", method = RequestMethod.POST, consumes = {"application/json"}, produces = {"application/json"}) 
@ResponseBody 
public List<TcPartVolumeDto> volumeinfo(@RequestBody TcPartDto partList) throws Exception { 
    return tcService.fetchVolumeInfo(partList); 
} 

하지만 다음 오류가 발생합니다.

우체부을 통해이 오류를 얻을 :

"Could not read document: Can not deserialize instance of tc.service.model.TcPartDto 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 tc.service.model.TcPartDto out of START_ARRAY token\n at [Source: [email protected]; line: 1, column: 1]"

내가 뭐하는 거지 무슨 문제

?

답변

0

당신이 그것을 읽고하려고 JSON 데이터와 일치하지 않는 창조하신 DTO :

그리고 당신은 경우에 대비하여 JSON 구조를 변경할 필요가 당신은 하나의 객체를 보낼. 당신의 DTO 샘플 JSON을 기반으로

은 다음과 같아야합니다

{ 
    "userId" : "someId", 
    "partNum" : [ "partNum1", "partNum2"] 
} 

당신이 다음 고정 소모하고 JSON 개체는 DTO는해야한다, 그렇지 않은 경우 :

public class MyDTO { 

    private String userId; 
    private String partNum; 

    // ... 
} 

과의 매개 변수와 컨트롤러와

종류

List<MyDTO> 
+0

이것은 저에게 적합합니다! 감사 –

0

public List<TcPartVolumeDto> volumeinfo(@RequestBody TcPartDto partList) 방법으로 JSON 배열을 보내고 있습니다. 그러나 하나의 객체로 비 순차 화되어야합니다 : TcPartDto partList.

은 하나의 TcPartDto를 보낼 JSON 구조를 변경하거나 확인

당신의 당신의 volumeinfo 방법은받을 수 Array 또는 List.

{ 
    "userId": 101, 
    "partNum": [ 
    "aaa", 
    "bbb", 
    "ccc" 
    ] 
} 
+0

다른 응용 프로그램에서 생성 된 JSON 형식을 변경할 수 없으며 그대로 사용해야합니다. –

0

다른 사람들이 이미 여러 가지 대답을 지적했듯이.

경우에 이것은 당신이 클래스 변경하지 않고 매핑 할 JSON 경우 :

JSON :

[{ 
    "userId":"101" 
}, 
{ 
    "partNum":"aaa" 
}, 
{ 
    "partNum":"bbb" 
}, 
{ 
    "partNum":"ccc" 
}] 

등급 :

@JsonIgnoreProperties(ignoreUnknown=true) 
public class TcPartDto { 

    private String userId; 
    private List<String> partNum; 
//getters and setters 
} 

컨트롤러 :

@RequestMapping(value = "/volumeinfo", method = RequestMethod.POST, consumes = {"application/json"}, produces = {"application/json"}) 
@ResponseBody 
public List<TcPartVolumeDto> volumeinfo(@RequestBody TcPartDto[] partArray) throws Exception { 
    return tcService.fetchVolumeInfo(partArray); 
} 

출력 :

[{"userId":"101","partNum":null},{"userId":null,"partNum":["aaa"]},{"userId":null,"partNum":["bbb"]},{"userId":null,"partNum":["ccc"]}] 
관련 문제