gpt4 book ai didi

json - 使用 EclipseLink MOXy (JAXB) 将子类编码为 JSON 时,是否有可能隐藏 "@type"条目?

转载 作者:行者123 更新时间:2023-12-04 21:24:14 26 4
gpt4 key购买 nike

我即将开发一个基于 JAX-RS 的 RESTful Web 服务,我使用 MOXy (JAXB) 来自动生成我的 Web 服务的 JSON 响应。

一切都很酷,但由于 Web 服务将是基于 JavaScript 的 Web 应用程序的后端,因此可公开访问,因此我不想公开某些细节,如类名等。

但是,我意识到在某些条件下,MOXy 会在编码字符串中嵌入一个“@type”条目,并且该条目后跟刚刚编码的对象的类名。

特别是,我已经意识到在编码扩展类的实例时 MOXy 的行为方式。

假设以下父类(super class)“MyBasicResponse”

@XmlRootElement(name="res")

public class MyBasicResponse {

@XmlElement
private String msg;

public MyBasicResponse() {
// Just for conformity
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}
}

而这个专门的(扩展的)类“MySpecialResponse”
@XmlRootElement(name="res")

public class MySpecialResponse extends MyBasicResponse {

@XmlElement
private String moreInfo;

public MySpecialResponse() {
// Just for conformity
}

public String getMoreInfo() {
return moreInfo;
}

public void setMoreInfo(String moreInfo) {
this.moreInfo = moreInfo;
}
}

因此,MyBasicResponse 对象的编码字符串是
{"msg":"A Message."}

(没关系!)

但是, MySpecialResponse 对象的编码字符串就像
{"@type":"MySpecialResponse","msg":"A Message.","moreInfo":"More Information."}

有没有办法去掉
"@type":"MySpecialResponse"

超出我的 react ?

最佳答案

您可以将对象包装在 JAXBElement 的实例中指定被编码的子类以摆脱类型键。下面是一个完整的例子。

Java模型

与问题相同,但以下 package-info添加到指定字段访问以匹配这些类的类

@XmlAccessorType(XmlAccessType.FIELD)
package com.example.foo;

import javax.xml.bind.annotation.*;

演示代码

演示

import java.util.*;
import javax.xml.bind.*;
import javax.xml.namespace.QName;

import org.eclipse.persistence.jaxb.JAXBContextProperties;

public class Demo {

public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(2);
properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
JAXBContext jc = JAXBContext.newInstance(new Class[] {MySpecialResponse.class}, properties);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

MySpecialResponse msr = new MySpecialResponse();
marshaller.marshal(msr, System.out);

JAXBElement<MySpecialResponse> jaxbElement = new JAXBElement(new QName(""), MySpecialResponse.class, msr);
marshaller.marshal(jaxbElement, System.out);
}

}

输出

我们看到当对象被编码时 type键被编码(对应于 XML 表示中的 xsi:type 属性),因为就 MOXy 而言,有必要区分 MyBasicResponseMySpecialResponse .当我们将对象包裹在 JAXBElement 的实例中时并限定 MOXy 类型不需要添加 type key 。
{
"type" : "mySpecialResponse"
}
{
}

想要查询更多的信息
  • http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
  • http://blog.bdoughan.com/2012/05/moxy-as-your-jax-rs-json-provider.html
  • 关于json - 使用 EclipseLink MOXy (JAXB) 将子类编码为 JSON 时,是否有可能隐藏 "@type"条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6417758/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com