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 中打开一个元素


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