简体   繁体   English

Collection的自定义序列化 <T> 使用杰克逊

[英]Custom serialization of Collection<T> using Jackson

I'd like to convert a java collection like this 我想转换像这样的java集合

public Collection<SomeDTO> getPages()
{
    return pages;
}

to a json array like this: 像这样的json数组:

pages: [{DTO}, {DTO}, {DTO}]

This works out of the box, but I'd now like to not use the default serialization for the SomeDTO . 这开箱即用,但我现在不想使用SomeDTO的默认序列化。 Specifically, I'd like to write out an object that includes a combination of the values and some additional calculations based on the SomeDTO . 具体来说,我想写出一个对象,其中包含值和基于SomeDTO一些额外计算的SomeDTO

I tried using the @JsonSerialize(using=Serializer) but when this is applied onto the Collection Method, it excpects me to serialize the collection myself. 我尝试使用@JsonSerialize(using=Serializer)但是当它应用于Collection Method时,它会让我自己序列化该集合。 It's doable, but I woudl prefer to simply define how JUST the DTOs are serialized. 这是可行的,但我更愿意简单地定义如何将DTO序列化。

Ideas? 想法?

This might not help immediately, but the problem with @JsonSerialize is that unlike @JsonDeserialize which has both "using" (for type itself, like ArrayList) and "contentUsing" (for value type); 这可能没有立即帮助,但@JsonSerialize的问题是,与@JsonDeserialize不同,它同时具有“using”(对于类型本身,如ArrayList)和“contentUsing”(对于值类型); @JsonSerialize does not have latter until Jackson 1.8 (it does exist in trunk). @JsonSerialize在Jackson 1.8之前没有后者(它确实存在于主干中)。

But you can register custom serializer for type SomeDTO if you want, and that will be used when serializing collections that have them as value types. 但是,如果需要,可以为SomeDTO类型注册自定义序列化程序,并在序列化将它们作为值类型的集合时使用。 There are multiple ways to register such custom serializers; 有多种方法可以注册这样的自定义序列化器; one is to just add @JsonSerializer(using=...) to declaration of SomeDTO. 一种是将@JsonSerializer(使用= ...)添加到SomeDTO的声明中。 And if you can not add it to class definition (third-party class), you can use mix-in annotations to associate annotations. 如果您无法将其添加到类定义(第三方类),则可以使用混合注释来关联注释。

您是否考虑过将getter添加到SomeDto以获取要序列化的其他字段?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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