简体   繁体   中英

How to exclude Weld metadata from JSON object serialization

Assume the following REST resource:

@Path("/ActiveLeadTask")
//Also possible MediaType.APPLICATION_XML
@Produces(MediaType.APPLICATION_JSON)
public class ActiveLeadTask {
    private @Inject ActiveLeadTaskBo activeLeadBo;

    @GET
    @Path("/getBo")
    public ActiveLeadTaskBo getBo() {
        return activeLeadBo;
    }
}
////////////////////////////////////////////////////
@XmlRootElement
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
public class ActiveLeadTaskBo implements Serializable {
    private static final long serialVersionUID = 1L;

    private String firstName;

    private String lastName;

    private String phoneNumber;
    private String phoneCountryCode;

    private AtomicInteger accessCounterField = new AtomicInteger(0);

    public ActiveLeadTaskBo() {
        firstName = "test";
        lastName = "test";
    }

    public int getAccessCounter() {
        return accessCounterField.incrementAndGet();
    }

    public void setAccessCounter(int seed) {
        accessCounterField.set(seed);
    }

    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

The REST response for getBo() JSON (but not for XML) returns the following:

{
  "accessCounter": 1,
  "firstName": "test",
  "lastName": "test",
  "metadata": {
    "contextualInstance": {
      "accessCounter": 2,
      "firstName": "test",
      "lastName": "test"
    },
    "instance": {
      "accessCounter": 3,
      "firstName": "test",
      "lastName": "test"
    }
  }
}

The JSON response contains an additional "metadata" field - how can I configure the project to not generate it, or avoid generating it? The CDI container is Weld and the JSON serializer is provided by Yasson.

Two solutions are possible:

  • create a wrapper class, for example, ActiveLeadTaskBoInjectWrapper:
@Inject
ActiveLeadTaskBoInjectWrapper activeLeadBo;


activeLeadBo.getInstance();
  • workaround Weld specifics:
@Inject
Foo foo;

public void doSomething() {
  if (foo instanceof WeldClientProxy) {
    // foo is a proxy
    ((WeldClientProxy)foo).getMetadata().getContextualInstance()
  } else {
    // not a proxy
  }
}

Depends on what JSON processing framework is used in your REST endpoint. For jsonb-api (jsr367) the only possible solution is to implement javax.json.bind.config.PropertyVisibilityStrategy to exclude generated properties from processing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM