My ParserCheck.java :-
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class ParserCheck {
public static void main(String[] args){
ObjectMapper objectMapper = new ObjectMapper();
String responseJson = "{\"status\":\"200\",\"message\":\"Success\"}";
InputStream streamResponse = IOUtils.toInputStream(responseJson);
try {
MyJsonResponse response = objectMapper.readValue(streamResponse, MyJsonResponse.class);
System.out.println(response);
} catch ( JsonParseException | JsonMappingException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
try {
MyJsonResponse response = objectMapper.readValue(streamResponse, MyJsonResponse.class);
System.out.println(response);
} catch ( JsonParseException | JsonMappingException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}finally{
try {
streamResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
My JsonResponse.java:
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;
@JsonIgnoreProperties(ignoreUnknown=true)
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class MyJsonResponse {
@JsonProperty
private Integer status;
@JsonProperty
private String message;
public Integer getStatus() {
return status;
}
public String getMessage() {
return message;
}
@Override
public String toString(){
return "Json Response [Status ="+ status +", Message =" + message + " ]";
}
}
I get the proper output the first time but the second time I get an exception. This is the output:
Json Response [Status =200, Message =Success ]java.io.EOFException: No content to map to Object due to end of input
at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2775)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2718)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1909)
at.service.provider.ParserCheck.main(ParserCheck.java:33)
What should be done in this case. I tried closing the stream after the first output but it still gives me the exception.
You're reusing a stream. the first call to
objectMapper.readValue(streamResponse, MyJsonResponse.class);
reads the stream to the end, so when you call it the second time, the stream has no more content. eg.
stremResponse.read() returns -1
Is there any reason you are using a stream? I tried:
MyJsonResponse response = objectMapper.readValue(responseJson, MyJsonResponse.class);
which works as expected.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.