Marshall / Unmarshall使用JAXB将JSON添加到Java类 [英] Marshall/Unmarshall a JSON to a Java class using JAXB

查看:134
本文介绍了Marshall / Unmarshall使用JAXB将JSON添加到Java类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JAX-RS和JAXB注释成功地将POJO编组为JSON。

I am successfully marshaling a POJO into JSON using JAX-RS and JAXB annotations.

问题是当我尝试使用相同的非编组时我的要求它不起作用。据我所知,文档 JAX-RS可以自动封送和解组应用程序/ json字符串回java类。

The problem is that when I am trying to use the same for un-marshalling my request it doesn’t work. As far as I can see in the documentation JAX-RS can automatically marshal and unmarshal application/json strings back to java classes.

我需要吗?为此创建我自己的MessageBodyReader,或者这个框架是否支持而不使用Jackson库?

Do I need to create my own MessageBodyReader for that, or this is supported by the framework without using Jackson libraries?

推荐答案

编组到XML很容易,但我花了一些时间来弄清楚如何编组JSON。找到解决方案后非常简单。

Marshalling to XML is easy, but it took me a while to figure out how to marshall to JSON. Pretty simple after you find the solution though.

public static String marshalToXml( Object o ) throws JAXBException {

    StringWriter writer = new StringWriter();
    Marshaller marshaller = JAXBContext.newInstance( o.getClass() ).createMarshaller();
    marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
    marshaller.marshal( o, writer );
    return writer.toString();
}

public static String marshalToJson( Object o ) throws JAXBException {

    StringWriter writer = new StringWriter();
    JAXBContext context = JSONJAXBContext.newInstance( o.getClass() );

    Marshaller m = context.createMarshaller();
    JSONMarshaller marshaller = JSONJAXBContext.getJSONMarshaller( m );
    marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
    marshaller.marshallToJSON( o, writer );
    return writer.toString();
}

这篇关于Marshall / Unmarshall使用JAXB将JSON添加到Java类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆