简体   繁体   中英

Java map object to several variants JSON

How can i map domain object to several variant JSON objects (several DTO), without chain DOMAIN_OBJECT->DTO->JSON? I have one big domain object and more than ten variants of representation. When I map domain object to specific DTO with structMap and then do serialization to JSON with jackson I spend a lot of time.

Is there any tool for map domain object to serveral variants JSON without midle layer DTO ?

It really depends on what your more than ten variants are like. Sometimes, sticking to DTOs can be the best approach, as described in this answer , where DTOs are used define the contract of REST APIs.

Alternatively, depending on your needs, you could play with @JsonView from Jackson. Using Spring? This answer may give you some insights.

I don't really know your use case, but as a note, if you use Jackson I presume you are using ObjectMapper . The ObjectMapper is an expensive object which you should reuse as much as possible (ergo, declare it static and final ), since it does a lot of caching behind the scene when the same object is converted lot of times.

Even better, get an ObjectWriter and/or ObjectReader from the ObjectMapper , which are immutable and thread-safe (ObjectMapper is tricky if you want to change its configuration at runtime), they should improve your performance.

Final thing, but I never went that far, you could write custom serializer / deserializer, but I see complexity going noticeably up (thus, it will be more difficult to mantain).

If you are working with strings, double check you use the StringBuilder (or StringBuffer on multi-threaded use case) and logging only when necessary ( if(logger.isDebugEnabled() { log.debug(...) } ), they are common pitfalls that bring performances down.

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