如何使用 JAXB 将属性对象转换为 JSON 对象
问题描述
我想在 REST 应用程序中接受和响应 JSON 对象.我需要发送和接收的数据位于 .properties 文件中.我已经阅读了它们,现在位于 Properties
对象中(来自 java.util.Properties
).有没有办法在不实现新类的情况下编组和解组 Properties
对象?
I want to accept and respond JSON objects in a REST Application. The data I need to send and receive are in a .properties file. I have already read them and are now in a Properties
Object(From java.util.Properties
). Is there a way to marshal and unmarshal Properties
Objects, without implementing a new class?
我在 Weblogic 服务器中使用 Jax-rs API.
I am using Jax-rs API in a Weblogic server.
推荐答案
对WebLogic不太熟悉,所以不知道它用的是什么版本的Jersey(1.x还是2.x),但是用的是1.x.x 你可以简单地添加这个依赖项
Not too familiar with WebLogic, so I don't know what version of Jersey it used (1.x or 2.x), but with the 1.x you can simply add this dependency
这将取决于杰克逊.Jackson 已经将 Properties
对象反序列化并序列化为 JSON 对象.
which will depend on Jackson. Jackson already deserializes and serializes the Properties
object to a JSON object.
这是一个简单的测试
资源
测试
结果:
配置方面,只需要配置POJOMapping Feature并注册Jackson提供者
For the configuration, you just need to configure the POJOMapping Feature and register the Jackson provider
程序化
web.xml
<小时>
使用 Jersey 2.x,它稍微简单一些.我们只需要这个提供者
With Jersey 2.x, it's a little bit simpler. We just need this provider
并注册相同的JacksonJaxbJsonProvider
(虽然包不同,但类名相同).无需 Pojo 映射功能.
And register the same JacksonJaxbJsonProvider
(though different package, the class name is the same). No Pojo Mapping Feature needed.
注意:在这两种情况下,都有两个 Jackson 提供程序,一个 JacksonJsonProvider
和一个 JacksonJaxbJsonProvider
.如果您希望 pojo 的编组依赖于 JAXB 注释,那么您应该注册后者.
Note: In both cases, there are two Jackson providers, a JacksonJsonProvider
and a JacksonJaxbJsonProvider
. If you want the marshalling of pojos to depend on JAXB annotations, then you should register the latter.
这篇关于如何使用 JAXB 将属性对象转换为 JSON 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!