I am using Jackson 2. When reading from remote service I obtain a JSON object like this:
{
"country":"1",
"complex":{
"link":"...",
"value":"..."
},
"test":""
}
so I have created the related POJOs for the purpose:
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"link",
"value"
})
public class Complex {
@JsonProperty("link")
private String link;
@JsonProperty("value")
private String value;
@JsonProperty("link")
public String getLink() {
return link;
}
@JsonProperty("link")
public void setLink(String link) {
this.link = link;
}
@JsonProperty("value")
public String getValue() {
return value;
}
@JsonProperty("value")
public void setValue(String value) {
this.value = value;
}
}
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"country",
"complex",
"test"
})
public class Resource {
@JsonProperty("country")
private String country;
@JsonProperty("complex")
private Complex complex;
@JsonProperty("test")
private String test;
@JsonProperty("country")
public String getCountry() {
return country;
}
@JsonProperty("country")
public void setCountry(String country) {
this.country = country;
}
@JsonProperty("complex")
public Complex getComplex() {
return complex;
}
@JsonProperty("complex")
public void setComplex(Complex complex) {
this.complex = complex;
}
@JsonProperty("test")
public String getTest() {
return test;
}
@JsonProperty("test")
public void setTest(String test) {
this.test = test;
}
}
so that I'm able to do:
Resource res = MAPPER.readValue(response.readEntity(String.class), Resource.class);
My problem is that, when executing POST requests, I need to send a different object, that is:
{
"country":"1",
"complex": "value",
"test":""
}
so where all "complex"
objects must be simply strings.
Any idea about how to handle this situation?
I have tried to create a JsonDeserializer
class:
public class ComplexValueDeserializer extends JsonDeserializer<Object> {
@Override
public Object deserialize(final JsonParser parser, final DeserializationContext deserializationContext)
throws IOException, JsonProcessingException {
final JsonToken jsonToken = parser.getCurrentToken();
if (jsonToken == null
|| (jsonToken == JsonToken.START_OBJECT && parser.getValueAsString().equals("{}"))) {
return "";
}
return null;
}
}
and add it to:
@JsonProperty("complex")
@JsonDeserialize(using = ComplexValueDeserializer.class)
private Complex complex;
but I get java.lang.IllegalArgumentException: argument type mismatch
error.
Thanks!
On your Complex Object type you can define a toString() method and then Annotate it with @JsonValue. This will indicate to Jackson that the returned result will be the value serialized for that object. You can them implement whatever logic you need there to represent the Complex type in the way you want. e.g.:
@JsonValue
public String toString() {
return value;
}