user1187958 user1187958 - 1 month ago 29
Java Question

@JsonProperty not working (Weblogic 12.2.1 and Java 8)

I'm having a problem where the JsonProperty annotation to change the name of a variable is not being honored. Here is the example app
https://github.com/derrylvarghese/problematicjson

I am converting the following JSON to POJO and then converting it back to JSON

String json = "{\"response\": {\"companyname\": \"ABC Company\",\"issn\": [{\"format\": \"paper\",\"val\": \"0018-9480\"},{\"format\": \"online\",\"val\": \"1557-9670\"}]},\"teststring\":\"testing me out\"}";

ObjectMapper mapper = new ObjectMapper();
WrapperObj record = mapper.readValue(json, WrapperObj.class);
ObjectWriter writer = mapper.writer();
writer.writeValue(response.getOutputStream(), record);


I am expecting the 'val' in the 'issn' object to show up as 'value' since i have a @JsonProperty("value") applied on the 'val' field.
Here is the output json (edited for brevity).

issn: [
{
format: "Print ISSN",
val: "0018-9480"
}
]


If i were to create an Issn object and do a record.getResponse.setIssn(setMyObject), the json output shows the proper JsonProperty tag. I am linking to a sample project that will show this if anyone is interested. (git link: https://github.com/derrylvarghese/problematicjson)

Update
Seems like since i annotated my POJO field with
@JsonProperty("value")
, the incoming JSON field should also be called 'value'. All this while i was seeing 'val' in the output because i had a catch all List field into which all the fields were going. I removed that JsonAnyGetter field and now my 'val' field does not show up.

Answer

OK so apparently sometime in the past Jackson may have supported one name for serialization and another for deserialization. Not anymore it seems. When i annotate a getter (getVal() ) with @JsonProperty("value"), it expects the incoming json payload to also have "value" (and not "val") eventhough i have a setVal() method.