Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson mixin annotation to include certain properties and exclude everything else

Tags:

json

jackson

cxf

I have a third party domain object that I wish to serialize to JSON using Jackson. There are a lot of properties on this accessible via public getters, but I am only interested in a very small subset of these. Since this is a third party object, I went with the mixin route. However, I couldn't find a good way to exclude everything from the original class other than the ones defined on the mixin interface. I tried to specify the @JsonIgnoreProperties on the mixin class, but it quickly gets out of hand with large number of properties to ignore. Any workarounds?

Thanks in advance!

EDIT: Adding some code

public class SpecialObject {
private String name;
private Integer id;
public String getName() {
    return name;
}
public Integer getId() {
    return id;
}
public String getFoo() {
    return "foo";
}
}

public interface SpecialObjectMixin {
    @JsonProperty
    String getName();
}

I was hoping that I will only get name in the serialized JSON. BTW, I am using this for restful calls via cxf-jaxrs with Jackson as the provider.

like image 610
Kilokahn Avatar asked Jan 30 '13 15:01

Kilokahn


People also ask

How do I ignore properties in ObjectMapper?

ObjectMapper; ObjectMapper objectMapper = new ObjectMapper(); objectMapper. configure(DeserializationFeature. FAIL_ON_UNKNOWN_PROPERTIES, false); This will now ignore unknown properties for any JSON it's going to parse, You should only use this option if you can't annotate a class with @JsonIgnoreProperties annotation.

How do I ignore JSON property?

To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.

What is Jackson mixin?

Jackson mixins is a mechanism to add Jackson annotations to classes without modifying the actual class. It was created for those cases where we can't modify a class such as when working with third-party classes. We can use any Jackson annotation but we don't add them directly to the class.


1 Answers

Figured out a way

@JsonAutoDetect(getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE)
public interface SpecialObjectMixin {

    @JsonProperty
    String getName();
}
like image 58
Kilokahn Avatar answered Sep 30 '22 18:09

Kilokahn