简体   繁体   中英

Jackson Custom Serializer for class with annotations

I have a complex object and for some of the nested objects I need to serialize them into JSON fields instead of JSON objects.

Eg.

public class Outer {
    private String someField;
    private AnotherClass anotherField;
}

public class AnotherClass {
    @XmlElement(name = "useThisName")
    private String someField;
    private String anotherField;
}

How can I make a custom serializer that will be for the nested object and obey the annotations so the fields are named properly?

My use case for this is to use the ObjectMapper.convertValue() method to create a Map so that I can loop through it and create NameValuePairs for a rest url.

In the end I am hoping to end up with a

Map<String, String> 

That I can loop over and create apache BasicNameValuePairs from.

Below is some code I want to use for the end result if I can get everything to serialize properly.

Map<String, String> parameters
        = DefaultJacksonMapper.getDefaultJacksonMapper().convertValue(obj, LinkedHashMap.class);

        return parameters
        .entrySet()
        .stream()
        .map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
        .collect(Collectors.toList());

If I convert this to a map now my output is like:

"someField" -> "data"
"anotherField" -> "size = 2"

I am trying to get the Map to have the following output which I feel like I need a custom serializer.

"someField" -> "data"
"useThisName" -> "data"
"anotherField" -> "data"

Ok I figured this out.

I ended up creating a new Module that inherited off of SimpleModule. Then I created a new Abstract class like

public abstract class OuterMixin {
    @JsonUnwrapped
    private AnotherClass anotherField;
}

I also had to annotate the AnotherClass with JsonProperty Like:

public class AnotherClass {
    @XmlElement(name = "useThisName")
    @JsonProperty("useThisName")
    private String someField;
    private String anotherField;
}

The when I got my Object Mapper I just registered my module with it and did the conversion and it all worked out.

As a side note I have another property that I had to write a custom serializer for and the @JsonUnwrapped did not work with that.

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