jakartaee / jsonb-api

Jakarta JSON Binding
https://eclipse-ee4j.github.io/jsonb-api/
Other
79 stars 39 forks source link

Feature request: @JsonbView #343

Open nimo23 opened 11 months ago

nimo23 commented 11 months ago

It would be great to have something like jacksons @JsonView in Json-B, maybe it can be called @JsonbView. It should work like the following example:

// enums to discriminate between different json views
public enum UserSubset{
    MY_SUBSET_1, 
    MY_SUBSET_2;
}

// the user class
public class User {

    private int id;

    @JsonbView("mysubset1")
    private String name;

    // UserSubset.MY_SUBSET_1 => UserSubset.MY_SUBSET_1.name() = "mysubset1"
    @JsonbView(UserSubset.MY_SUBSET_1)
    private Task task;
}

// the task class
public class Task {

    private int id;

    // property will be (de)serialized in mysubset1, mysubset2 and the default one
    @JsonbView("mysubset1, mysubset2")
    private String description;
}

The value of @JsonbView is a common (array of) String or Enum which is used as a discriminator. Using something like

jsonb.toJson(user, "mysubset"); or jsonb.toJson(user, UserSubset.MY_SUBSET_1);

will outut the json with only the properties annotated with @JsonbView("mysubset1") or @JsonbView(UserSubset.MY_SUBSET_1)

Is something like this already planned?

I think it would be an extremely useful and simple approach to declare various JSON subviews quickly, easily and cleanly.