栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JAXB映射到JSON

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAXB映射到JSON

注意: 我是 Eclipselink
JAXB(MOXy)的
负责人,并且是
JAXB(JSR-222) 专家组的成员。

如果杰克逊无法做到这一点,那么用例将适用于MOXy。

Java模型

oo

这是一个示例类,其中包含type字段

JAXBElement

import javax.xml.bind.JAXBElement;import javax.xml.bind.annotation.*;@XmlAccessorType(XmlAccessType.FIELD)public class Foo {    @XmlElementRef(name="bar")    private JAXBElement<Bar> bar;}

酒吧

public class Bar {}

对象工厂

import javax.xml.bind.JAXBElement;import javax.xml.bind.annotation.*;import javax.xml.namespace.QName;@XmlRegistrypublic class ObjectFactory {    @XmlElementDecl(name = "bar")    public JAXBElement<Bar> createBar(Bar bar) {        return new JAXBElement<Bar>(new QName("bar"), Bar.class, bar);    }}

独立演示代码

下面是一些可以在Java SE中运行的演示代码,以查看一切正常:

演示版

import java.util.*;import javax.xml.bind.*;import javax.xml.transform.stream.StreamSource;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[] {Foo.class, ObjectFactory.class}, properties);        Unmarshaller unmarshaller = jc.createUnmarshaller();        StreamSource json = new StreamSource("src/forum19158056/input.json");        Foo foo = unmarshaller.unmarshal(json, Foo.class).getValue();        Marshaller marshaller = jc.createMarshaller();        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);        marshaller.marshal(foo, System.out);    }}

input.json /输出

{"bar" : {} }

使用JAX-RS运行

以下链接将帮助您在JAX-RS服务中利用MOXy:

  • http://blog.bdoughan.com/2012/05/moxy-as-your-jax-rs-json-provider.html
  • http://blog.bdoughan.com/2013/06/moxy-is-new-default-json-binding.html


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/595108.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号