JsonSerialize / JsonDeserialize not working in Apa

2019-06-07 12:15发布

问题:

LATER EDIT 2019-05-31

If I write a sample main method which instantiates an Item and then call String s = new ObjectMapper().writeValueAsString(item);, then the custom serializer is called correctly and has effect.

The issue only appears when the whole app is deployed in an Apache TomEE server.


LATER EDIT: it's not an issue with placement of annotation (on field vs. on getter), I tried various combinations of this (annotation on getter, annotation on private field, annotation on public field, etc...)


The code:

import com.fasterxml.jackson....
// YES, all JSON-related stuff is from fasterxml

@JsonAutoDetect
public class Item {
    private Date lastModified;

    @JsonSerialize(using = CSer.class)
    public Date getLastModified() {
        return lastModified;
    }

    public class CSer extends JsonSerializer<Date> {
        public SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

        @Override
        public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers)
                throws IOException, JsonProcessingException {
            gen.writeString(dateFormat.format(value));
        }
    }
}

// some place else, in a REST service class
    ...
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getItems(... {
        ...
        return Response.ok(result.getData()).build();
        // result.getData() is an ArrayList of "Item" objects.
    }

The ISSUES:

  • from what I know, the default JSON output format of the date should be the timestamp. In my case, it's not, instead it's yyyyMMddHHmmssZ
  • the custom serializer has no effect, I cannot change the output format of the date, and the serialize method never gets called.

The jackson files in my lib folder: jackson-annotations-2.8.0.jar, jackson-core-2.8.8.jar, jackson-databind-2.8.8.1.jar.

What am I doing wrong ?

Thank you.

回答1:

It might have something to do with your annotation being placed on the getter - you might move it to reflect something similar to

public class Item {

    @JsonSerialize(using = CSer.class)
    private Date lastModified;

   // ...
}

or you have to configure Jackson to only use getters for serialization.