[英]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? 如何在没有链DOMAIN_OBJECT-> DTO-> JSON的情况下将域对象映射到几个不同的JSON对象(几个DTO)? 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. 当我使用
structMap
将域对象映射到特定的DTO,然后使用jackson将序列化到JSON时,我花费了大量时间。
Is there any tool for map domain object to serveral variants JSON without midle layer DTO ? 是否有任何工具可以将域对象映射到不带中间层DTO的服务器变体JSON?
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.
有时,坚持DTO可能是最好的方法,如本答案所述 ,其中使用DTO定义REST API的约定。
Alternatively, depending on your needs, you could play with @JsonView
from Jackson. 另外,根据您的需要,您可以使用Jackson的
@JsonView
玩。 Using Spring? 使用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
. 我真的不知道您的用例,但是请注意,如果您使用Jackson,我想您正在使用
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. ObjectMapper
是一个昂贵的对象,您应该尽可能地重用(ergo,将其声明为static
和final
),因为当多次转换同一对象时,它会在后台进行大量缓存。
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. 更好的是,从
ObjectMapper
获得ObjectWriter
和/或ObjectReader
,它们是不可变的并且是线程安全的(如果要在运行时更改其配置,ObjectMapper会很棘手),它们应该可以提高性能。
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. 如果使用的是字符串,请仔细检查是否使用StringBuilder(或在多线程用例中使用StringBuffer),并仅在必要时进行日志记录(
if(logger.isDebugEnabled() { log.debug(...) }
),它们是导致表演下降的常见陷阱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.