programing

입력 종료 잭슨 파서로 인해 매핑할 콘텐츠가 없습니다.

luckcodes 2022. 10. 18. 22:01

입력 종료 잭슨 파서로 인해 매핑할 콘텐츠가 없습니다.

로부터 이 .{"status":"true","msg":"success"}

Jackson 파서 라이브러리를 사용하여 이 json 문자열을 해석하려고 합니다만, 다음과 같은 mapping-exception이 발생하고 있습니다.

com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
 at [Source: java.io.StringReader@421ea4c0; line: 1, column: 1]

왜 이런 예외가 생기는 거죠?

이 예외의 원인을 이해하려면 어떻게 해야 합니까?

다음 방법으로 해석하려고 합니다.

StatusResponses loginValidator = null;

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(Feature.AUTO_CLOSE_SOURCE, true);

try {
    String res = result.getResponseAsString();//{"status":"true","msg":"success"}
    loginValidator = objectMapper.readValue(result.getResponseAsString(), StatusResponses.class);
} catch (Exception e) {
    e.printStackTrace();
}

StatusResponse 클래스

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "status","msg" })
public class StatusResponses {

    @JsonProperty("status")
    public String getStatus() {
        return status;
    }

    @JsonProperty("status")
    public void setStatus(String status) {
        this.status = status;
    }

    @JsonProperty("msg")
    public String getMessage() {
        return message;
    }

    @JsonProperty("msg")
    public void setMessage(String message) {
        this.message = message;
    }

    @JsonProperty("status")
    private String status;

    @JsonProperty("msg")
    private String message;

    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonGetter
    public Map<String, Object> getAdditionalProperties() {
        return additionalProperties;
    }

    @JsonSetter
    public void setAdditionalProperties(Map<String, Object> additionalProperties) {
        this.additionalProperties = additionalProperties;
    }
}
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.ObjectMapper;

StatusResponses loginValidator = null;

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(Feature.AUTO_CLOSE_SOURCE, true);

try {
    String res = result.getResponseAsString();//{"status":"true","msg":"success"}
    loginValidator = objectMapper.readValue(res, StatusResponses.class);//replaced result.getResponseAsString() with res
} catch (Exception e) {
    e.printStackTrace();
}

어떻게 작동했는지, 왜 작동했는지 알 수 없습니다. :(하지만 작동했습니다.

이 문제는 null InputStream을 ObjectMapper.readValue 호출에 전달한 것이 원인입니다.

ObjectMapper objectMapper = ...
InputStream is = null; // The code here was returning null.
Foo foo = objectMapper.readValue(is, Foo.class)

이것이 이 예외의 가장 일반적인 이유라고 생각합니다.

나는 이 오류를 고칠 수 있다.제 경우, 문제는 클라이언트 측에 있었습니다.서버에 쓰던 스트림을 실수로 닫지 않았습니다.스트림을 닫았는데 잘 작동했어요.에러도, 서버가 입력의 끝을 특정할 수 없었던 것처럼 들립니다.

OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
out.write(jsonstring.getBytes());
out.close() ; //This is what I did

문제는 다음과 같은 답변을 두 번 읽은 것입니다.

System.out.println(response.body().string());
getSucherResponse = objectMapper.readValue(response.body().string(), GetSucherResponse.class);

그러나 응답은 스트림이기 때문에 한 번만 읽을 수 있습니다.

오늘도 비슷한 오류가 발생했는데, 게시 요청의 내용 유형 헤더에 문제가 있었습니다.콘텐츠 유형이 예상대로인지 확인하십시오.는 a입니다.multipart/form-datacontent-type API 되었습니다.application/json.

이 에러는 때때로(흔히) 발생합니다.실제 문제를 숨깁니다.장애 상태가 원인이 되어 콘텐츠가 잘못되어 시리얼화 해제에 실패할 수 있습니다.

경우,의 마크를 하기 전에 하는 것을 는 인증 에러가 에, 「」, 「HTTP」의 이 된 입니다.=> 실제 문제는 인증 오류가 발생한 것입니다.이 때문에401 Unauthorized 그 빈에, 나는 이것을 받고 있었다.No content to map due to end-of-input인증 문제에 대한 단서를 얻지 못했습니다.

집배원과 함께 GET 요청을 보낼 때 이 오류가 발생했습니다.요청에 매개 변수가 필요하지 않습니다.저의 실수는 요청 본문에 빈 줄이 있었다는 것입니다.

제 경우 요청이 처리되기 전에 요청 본문을 기록하기 위해 서버 측에서 작성한 저지 RequestEventListener에서 스트림을 읽고 있었습니다.그 결과, 그 후의 판독 결과(비즈니스 로직의 실행시에 건네지는 것)는 아무것도 얻을 수 없는 것이 아닌가 하는 것을 깨달았습니다.저는 그것이 사실임을 확인했습니다.

따라서 스트림을 사용하여 JSON 문자열을 읽는 경우에는 이 점에 주의하십시오.

간단한 수정은Content-Type: application/json

응답을 얻기 위해 REST API 호출을 하고 있을 것입니다.

대부분의 경우 설정되지 않습니다.Content-Type: application/json당신이 요청할 때. Content-Type: application/x-www-form-urlencoded이 예외의 원인이 되고 있는 것이 선택됩니다.

이상하다는 건 알지만 클라이언트 측과 서버 측 모두에서 GetMappingPostMapping으로 변경하자 오류가 사라졌습니다.

클라이언트와 서버는 모두 스프링 부트프로젝트입니다.

제 경우 파일을 동시에 읽고 쓰려고 하는 두 스레드 간의 레이스 조건이 있었습니다.파일에 쓰고 읽는 메서드에 "synchronized" 키워드를 추가했더니 오류가 사라졌습니다.

이 문제에 대해 너무 깊이 생각하지 말고 여기서 null 포인터 예외를 처리해 주세요.응답이 null로 수신되면 해결 방법이 나옵니다.

한 명은@JsonProperty("status")그리고.@JsonProperty("msg")는 필드를 선언할 때만 존재해야 하며 설정자와 게터에는 존재하지 않습니다.

사실, 이것을 해석하는 가장 간단한 방법은

@JsonAutoDetect  //if you don't want to have getters and setters for each JsonProperty
public class StatusResponses {

   @JsonProperty("status")
   private String status;

   @JsonProperty("msg")
   private String message;

}

언급URL : https://stackoverflow.com/questions/26925058/no-content-to-map-due-to-end-of-input-jackson-parser