Unwrap a element in Jackson/Jaxb(在 Jackson/Jaxb 中打开一个元素)
问题描述
我正在使用 Jersey+Jackon 制作一个与 JSON 配合使用的 REST API.
假设我有一个类如下:
@XmlRootElement公共类 A {公共字符串;}
这是我使用该类的球衣方法:
<代码>@GET@Produces(MediaType.APPLICATION_JSON)public Object get(@PathParam("id") String id) 抛出异常{A[] a= 新 A[2];a[0] = 新的 A();a[0].s="abc";a[1] = 新的 A();a[1].s="def";返回一个;}
输出是:
{"a":[{"s":"abc"},{"s":"def"}]}
但我希望它是这样的:
[{"s":"abc"},{"s":"def"}]
我该怎么办?请帮帮我.
您的要求似乎是从 json 字符串中删除根元素.这可以在 Jersey 中进行如下配置.在 Jersey 中,是否删除根元素由 JSONConfiguration.rootUnwrapping()
配置.可以在 Jersey 和 CXF 中的 JSON 支持中找到更多详细信息..p>
这是执行此操作的示例代码.
@Provider公共类 MyJAXBContextResolver 实现 ContextResolver{私有 JAXBContext 上下文;私有类[] 类型 = {StatusInfoBean.class, JobInfoBean.class};公共 MyJAXBContextResolver() 抛出异常 {this.context = 新的 JSONJAXBContext(JSONConfiguration.mapped().rootUnwrapping(真).arrays("工作").nonStrings("pages", "tonerRemaining").建造(),类型);}公共 JAXBContext getContext(Class<?> objectType) {返回(类型[0].equals(objectType))?上下文:空;}}
I am using Jersey+Jackon to make a REST API which works with JSON.
Assume that I have a class as follows:
@XmlRootElement
public class A {
public String s;
}
and here is my jersey method which uses the class:
@GET
@Produces(MediaType.APPLICATION_JSON)
public Object get(@PathParam("id") String id) throws Exception{
A[] a= new A[2];
a[0] = new A();
a[0].s="abc";
a[1] = new A();
a[1].s="def";
return a;
}
the out put is:
{"a":[{"s":"abc"},{"s":"def"}]}
but I want it to be like this:
[{"s":"abc"},{"s":"def"}]
What should I do? Please help me.
Your requirement seems to be to drop the root element from json string. This can be configured in Jersey as follows.
In Jersey, whether dropping root element is configured by JSONConfiguration.rootUnwrapping()
. More details can be found in JSON support in Jersey and CXF.
Here's a sample code that does this.
@Provider
public class MyJAXBContextResolver implements ContextResolver<JAXBContext> {
private JAXBContext context;
private Class[] types = {StatusInfoBean.class, JobInfoBean.class};
public MyJAXBContextResolver() throws Exception {
this.context = new JSONJAXBContext(
JSONConfiguration.mapped()
.rootUnwrapping(true)
.arrays("jobs")
.nonStrings("pages", "tonerRemaining")
.build(),
types);
}
public JAXBContext getContext(Class<?> objectType) {
return (types[0].equals(objectType)) ? context : null;
}
}
这篇关于在 Jackson/Jaxb 中打开一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Jackson/Jaxb 中打开一个元素


- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01