简体   繁体   中英

Adjust the object before returning the JSON response in Apache Camel with Jackson

I'm using Apache Camel to build a REST POST endpoint that takes and object and returns another object as JSON:

from("direct:toProcessor").
        routeId("routeId").
        log(">>> ${body}").
        process(myProcessor);

rest("/api").
        id("route1").
        consumes("application/json").
        post("/test").
        bindingMode(RestBindingMode.json).
        type(RqObj.class).
        outType(RsObj.class).
        to("direct:toProcessor");

the MyProcessor.java class makes all the logic to use the RqObj object and build the RsObj response.

That works and I see the JSON response, but there is a problem, the RsObj contains dates as XMLGregorianCalendar with a specific timezone (and I cannot edit the definition of RsObj.java , because it's coming from an external dependency), so even if I set a date field to 2021-05-12T10:00:00.000+0000 at the end the returned JSON shows something else: 2021-05-12T08:00:00.000+0000 (different hour).

So I would like either to edit that field somehow during the serialization / deserialization process, or just customizing Jackson so that it uses a specific date format.

For instance, I made some attempts to tell Camel to use a customized ObjectMapper (as following):

ObjectMapper myObjectMapper = new ObjectMapper().setDateFormat(new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"));

and using it in one of the following ways:

JacksonDataFormat jacksonDataFormat = new JacksonDataFormat(myObjectMapper, null);
final DataFormatDefinition dataFormatDefinition = new JsonDataFormat();
dataFormatDefinition.setDataFormat(jacksonDataFormat);
final Map<String, DataFormatDefinition> map = new HashMap<>();
map.put("json", dataFormatDefinition);
getContext().
        setDataFormats(map);

or:

from("direct:toProcessor").
        routeId("routeId").
        log(">>> ${body}").
        process(myProcessor).
        marshal(new JacksonDataFormat(myObjectMapper, CheckResponse.class)).
        unmarshal(new JacksonDataFormat(myObjectMapper, CheckResponse.class))

but none of those changes the result.

So what would it be your solution here?

Is there a way to tell Camel to adjust the response before returning is as JSON or what's the right way to customize Jackson in order to let it do it?

Thanks

Based on your input I could see, the external entity is doing some kind of processing.

If date timezone is your problem, probably,try converting the date to UTC before setting it in the object.

But if you want to have objectMapper do a special work for you, then you can define a custom object mapper

Customizing JSON Serializer

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM