Skip to content

Instantly share code, notes, and snippets.

@varren
Last active May 19, 2016 09:26
Show Gist options
  • Save varren/38b76c4a62fc5024caedcdc469606649 to your computer and use it in GitHub Desktop.
Save varren/38b76c4a62fc5024caedcdc469606649 to your computer and use it in GitHub Desktop.
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.module.SimpleModule;
import java.io.IOException;
import java.util.List;
public class Main {
private static final String json ="{\"result\": \"some result\"}";
private static final String json2 ="\"ERROR\"";
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(SearchResultDTO.class, new SearchResultsDeserializer());
mapper.registerModule(module);
SearchResultDTO obj1 = mapper.readValue(json,SearchResultDTO.class);
SearchResultDTO obj2 = mapper.readValue(json2,SearchResultDTO.class);
System.out.println(obj1);
System.out.println(obj2);
}
private static class SearchResultDTO {
private String result;
public SearchResultDTO() {
}
public SearchResultDTO(String result) {
this.result = result;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
@Override
public String toString() {
return "SearchResultDTO{" +
"result='" + result + '\'' +
'}';
}
}
public static class SearchResultsDeserializer extends JsonDeserializer<SearchResultDTO> {
private static ObjectMapper mapper = new ObjectMapper();
@Override
public SearchResultDTO deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
JsonToken t = jp.getCurrentToken();
if (t == JsonToken.VALUE_STRING){
return new SearchResultDTO(jp.getText());
} else {
return mapper.readValue(jp, SearchResultDTO.class);
}
}
}
}
@varren
Copy link
Author

varren commented May 19, 2016

Output:
SearchResultDTO{result='some result'}
SearchResultDTO{result='ERROR'}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment