Marshall/Unmarshall a JSON to a Java class using JAXB(使用 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();
}
这篇关于使用 JAXB 将 JSON 编组/解组到 Java 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 JAXB 将 JSON 编组/解组到 Java 类


基础教程推荐
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01