【问题标题】:How to exclude Weld metadata from JSON object serialization如何从 JSON 对象序列化中排除 Weld 元数据
【发布时间】:2019-11-18 22:25:31
【问题描述】:

假设以下 REST 资源:

@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;
    }
}

getBo() JSON(但不是 XML)的 REST 响应返回以下内容:

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

JSON 响应包含一个额外的“元数据”字段 - 如何将项目配置为不生成它,或者避免生成它? CDI 容器是 Weld,JSON 序列化程序由 Yasson 提供。

【问题讨论】:

  • 一种可能的解决方案是简单地使用包装对象:ActiveLeadTaskBoInjectWrapper activeLeadBo; 然后将其用作:return activeLeadBo.getInstance();

标签: jax-rs jboss-weld yasson


【解决方案1】:

取决于 REST 端点中使用的 JSON 处理框架。对于 jsonb-api (jsr367),唯一可能的解决方案是实现 javax.json.bind.config.PropertyVisibilityStrategy 以排除处理生成的属性。

【讨论】:

    【解决方案2】:

    有两种可能的解决方案:

    • 创建一个包装类,例如 ActiveLeadTaskBoInjectWrapper:
    @Inject
    ActiveLeadTaskBoInjectWrapper activeLeadBo;
    
    
    activeLeadBo.getInstance();
    
    • 解决方法 焊接细节:
    @Inject
    Foo foo;
    
    public void doSomething() {
      if (foo instanceof WeldClientProxy) {
        // foo is a proxy
        ((WeldClientProxy)foo).getMetadata().getContextualInstance()
      } else {
        // not a proxy
      }
    }
    

    【讨论】:

    猜你喜欢
    • 2011-03-17
    • 2012-04-27
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多