您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

生成json时能否使MOXy不输出属性?

生成json时能否使MOXy不输出属性?

由于您的JSON绑定与XML绑定略有不同,因此我将使用 的外部映射文件

在外部映射文件中,我们会将type字段标记为瞬态。

<?xml version="1.0"?>
<xml-bindings
    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
    package-name="forum383861">
    <java-types>
        <java-type name="ReleaseGroup">
            <java-attributes>
                <xml-transient java-attribute="type"/>
            </java-attributes>
        </java-type>
    </java-types>
</xml-bindings>

以下是本示例将使用的域模型。请注意该type属性是如何用注释的@XmlAttribute

package forum383861;

import javax.xml.bind.annotation.*;

@XmlRootElement(name="release-group")
@XmlAccessorType(XmlAccessType.FIELD)
public class ReleaseGroup {

    @XmlAttribute
    String type;

    String title;

}

要将MOXy指定为JAXB提供程序,您需要jaxb.properties在与域模型相同的程序包中包含一个名为的文件,并包含以下条目(请参阅:http : //blog.bdoughan.com/2011/05/specifying- eclipselink-moxy-as -your.html)。

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

由于XML和JSON表示形式不同,因此我们将为其分别创建JAXBContexts。对于JSON,我们将利用MOXy的外部映射文件

package forum383861;

import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;

public class Demo {

    public static void main(String[] args) throws Exception {
        ReleaseGroup rg = new ReleaseGroup();
        rg.type = "Album";
        rg.title = "Fred";

        // XML
        JAXBContext xmlJC = JAXBContext.newInstance(ReleaseGroup.class);
        Marshaller xmlMarshaller = xmlJC.createMarshaller();
        xmlMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        xmlMarshaller.marshal(rg, System.out);

        // JSON
        Map<String, Object> properties = new HashMap<String, Object>(2);
        properties.put(JAXBContextProperties.OXM_MetaDATA_SOURCE, "forum383861/oxm.xml");
        properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
        JAXBContext jsonJC = JAXBContext.newInstance(new Class[] {ReleaseGroup.class}, properties);
        Marshaller jsonMarshaller = jsonJC.createMarshaller();
        jsonMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jsonMarshaller.marshal(rg, System.out);
    }

}

以下是运行演示代码输出

<?xml version="1.0" encoding="UTF-8"?>
<release-group type="Album">
   <title>Fred</title>
</release-group>
{
   "release-group" : {
      "title" : "Fred"
   }
}
其他 2022/1/1 18:28:47 有415人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶