Here is my class structure:

public class Business {
    public long id;
    public List<Employee> employees;
    // constructors, getters, setters
}
public class BusinessParcelable extends Business implements Parcelable {
    // some functions, not additional fields
}

public class Employee {
    // fields, constructor, getters, setters
}
public class EmployeeParcelable extends Employee implements Parcelable {
    // some functions, no additional fields
}

If I serialize it into a JSON string using the following code:

someFunction(BusinessParcelable b) {
    ObjectMapper objectMapper = new ObjectMapper();
    Business base = (Business)b;
    String jsonString = objectMapper.writeValueAsString(base);
}

The jsonString looks like:

{
    "id": 15,
    "employees": [
        {
            ...
        }
    ],
    "employeesParcelable": [
        {
            ...
        }
    ]
}

I do not want employees and employeesParcelable duplicated in my JSON string. I am able to solve it by replacing:

Business base = (Business)b;

With:

Business base = new Business();
base.setXXX(b.getXXX());
base.setYYY(b.getYYY());
base.setZZZ(b.getZZZ());

But I want to avoid this deep copy as my class structure has a lot of fields and is multiple levels deep. Is there are way in jackson to avoid duplicating the base and derived list (through some simple annotations)?

Edit: I was just able to get the desired result using Google Gson:

Gson gson = new Gson();
String jsonUsingGson = gson.toJson(base);

It would still be good to know how to get the same result using Jackson though.

有帮助吗?

解决方案

I think, that your Parcelable interface contains getEmployeesParcelable method. By default Jackson serializes all getters. To avoid this, you can annotate your method in this way:

interface Parcelable {

    @JsonIgnore
    List<Employee> getEmployeesParcelable();

    //other methods
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top