【发布时间】:2013-04-26 04:44:43
【问题描述】:
在下面的格式中,我怀疑每个字段都提到的类型。你能建议一些解决方案吗?这是将要使用它的第三方的要求。
主题“:{ “类型”:“字符串”, "$":"机柜型号?" }
【问题讨论】:
-
使用 Jackson 2,见 stackoverflow.com/q/6542833/100836
在下面的格式中,我怀疑每个字段都提到的类型。你能建议一些解决方案吗?这是将要使用它的第三方的要求。
主题“:{ “类型”:“字符串”, "$":"机柜型号?" }
【问题讨论】:
我使用谷歌的 gson API 完成了这项工作。编写了一个自定义序列化程序,它检查类型和值并基于它创建 JSON 对象。
【讨论】:
注意:我是EclipseLink JAXB (MOXy) 领导,也是JAXB (JSR-222) 专家组的成员。
以下是如何使用 MOXy 的 JSON 绑定来完成此操作。
域模型(根)
@XmlElement 注解可用于指定属性的类型。将类型设置为Object 将强制写入符合条件的类型。
import javax.xml.bind.annotation.*;
public class Root {
private String subject;
@XmlElement(type=Object.class)
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
}
演示
由于将编组一个类型限定符,因此需要为该值写入一个键。默认为value。您可以使用JSON_VALUE_WRAPPER 属性将其更改为$。
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(3);
properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
properties.put(JAXBContextProperties.JSON_VALUE_WRAPPER, "$");
JAXBContext jc = JAXBContext.newInstance(new Class[] {Root.class}, properties);
Root root = new Root();
root.setSubject("Cabinet model number?");
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
输出
下面是运行演示代码的输出。
{
"subject" : {
"type" : "string",
"$" : "Cabinet model number?"
}
}
更多信息
【讨论】: