0

I want to write a function that only serializes a POJO with given implicit field names.

For example,

class Car{
    public int id;
    public String type;
    public Manufacture manufacture;
}

Class Manufacture{
   public int id;
   public String name;
}

if I want to serialize a Car object with a given list(i.e. [Car.id, Car.Manufacture.name]) Then I want to get

{
    Car:{
        id: xxx,
        Manufacture: {
            name: xxx
        }
    }
}

Another example, given list = [Car.type]
Then I should get

{
    Car:{
        type: xxx
    }
}

I am currently trying to override the serializeAsField method to check if the field is in the given list, but the problem here is that I don't know the depth, then I cannot correctly compare the current field with the list.

How could I achieve it? Are there any other ways?

  • What is your goal? Can you provide an example of what you get vs. what you expected? The question is not clear. – tucuxi Oct 26 '21 at 10:19
  • How do you currently serialize your data as JSON? Which API are you using? Please [edit] your question to include the relevant source code you have, if possible as a [mcve]. – Progman Oct 26 '21 at 18:25

1 Answers1

2

Mark the unwanted fields with the @JsonIgnore annotation.

On-the-fly filtering
Here is a Baeldung article that discusses using a filter to determine which fields are serialized: https://www.baeldung.com/jackson-serialize-field-custom-criteria

I suspect that is the answer you want.

DwB
  • 37,124
  • 11
  • 56
  • 82