0

I don't expect this will be a tough question, but with all that Jackson has to offer, I hope there is a solution that will work for me. Am using Java 11 now.

Let's say I have an object that looks like this:

public class MyMainObject() {
    private Long id;
    private String myName;
    private SomeObject someObject;
    ... getters/setters
}
public class SomeObject() {
    private Long someId;
    private String someName;
}

Now, I know I can use Jackson to convert this code as follows to json:

MyMainObject myMainObject = new MyMainObject();
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(myMainObject);

I know that this will give me the entirety of 'SomeObject' in the JSON, which is fine. But now, I just want to get the 'someId' field from 'SomeObject'.

I am wondering if there is some Jackson Annotation I could use in the 'MyMainObject' with the field 'someObject' so I only get the 'someId' from 'SomeObject'.

I suppose I could forget this and just do a mapping from these two objects to some other DTO. Or, I could put @JsonIgnore for the SomeObject.someName and that would work also. But in this case, imagine SomeObject has many more fields than the ones I listed, and I don't want to use @JsonIgnore for all those fields.

So, if there is a quick Jackson Annotation I could use to just get the one field from the SomeObject, that would be great. I'll keep checking the Jackson Annotations to see if there is something.

tjholmes66
  • 1,850
  • 4
  • 37
  • 73
  • Does this answer your question? [Jackson: Serialize only marked fields](https://stackoverflow.com/questions/22668374/jackson-serialize-only-marked-fields) – Youans Jun 12 '23 at 21:14

1 Answers1

2

If I understand you query correctly, you'd like to include just a single property of SomeObject when serializing it using Jackson. If that's correct, then I think @JsonIncludeProperties class annotation might be a good fit. Something along these lines:

@JsonIncludeProperties({"someId"})
public class SomeObject {
    private Long someId;
    private String someName;
// other properties to be ignored when serializing
...
// getters/setters

}

The output result would not include other properties of SomeObject in the serialization (only the property/properties specified by @JsonIncludeProperties):

{"id":null,"myName":null,"someObject":{"someId":123}}

It was added in Jackson Release 2.12: https://github.com/FasterXML/jackson/wiki/Jackson-Release-2.12#jsonincludeproperties

Additional details linked from the GitHub release post: https://cowtowncoder.medium.com/jackson-2-12-most-wanted-2-5-bc45ef53ede7

R4N
  • 2,455
  • 1
  • 7
  • 9