Java 我们如何使用XStream或任何其他解析器获得以下格式的json?
在下面的格式中,我怀疑的是每个字段中提到的类型。你能提出一些解决办法吗?这是第三方的要求,第三方将使用此产品 主题“:{ “类型”:“字符串”, “$”:“机柜型号?”Java 我们如何使用XStream或任何其他解析器获得以下格式的json?,java,json,xstream,Java,Json,Xstream,在下面的格式中,我怀疑的是每个字段中提到的类型。你能提出一些解决办法吗?这是第三方的要求,第三方将使用此产品 主题“:{ “类型”:“字符串”, “$”:“机柜型号?” }注意:我是专家组的负责人和成员 下面是如何使用MOXy的JSON绑定实现这一点 域模型(根) @xmlement注释可用于指定属性的类型。将类型设置为对象将强制写出符合条件的类型 import javax.xml.bind.annotation.*; public class Root { private Stri
}注意:我是专家组的负责人和成员 下面是如何使用MOXy的JSON绑定实现这一点 域模型(根)
@xmlement
注释可用于指定属性的类型。将类型设置为对象将强制写出符合条件的类型
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\u value\u包装器
属性将其更改为$
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);
}
}
了解更多信息
注意:我是专家组的负责人和成员
下面是如何使用MOXy的JSON绑定实现这一点
域模型(根)
@xmlement
注释可用于指定属性的类型。将类型设置为对象将强制写出符合条件的类型
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\u value\u包装器
属性将其更改为$
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);
}
}
了解更多信息
我使用谷歌的gson API完成了这项工作。编写了一个自定义序列化程序,用于检查类型和值,并基于此创建JSON对象。我使用谷歌的gson API完成了这项工作。编写了一个自定义序列化程序,用于检查类型和值,并基于此创建JSON对象。使用Jackson 2,请参阅使用Jackson 2,请参阅