Aar*_*n T 2 json jaxb jettison
我有传入的JSON字符串,我需要解组到JAXB注释对象.我正在使用jettison这样做.JSON字符串如下所示:
{
objectA :
{
"propertyOne" : "some val",
"propertyTwo" : "some other val",
objectB :
{
"propertyA" : "some val",
"propertyB" : "true"
}
}
}
Run Code Online (Sandbox Code Playgroud)
ObjectA代码如下所示:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "objectA")
public class ObjectA {
@XmlElement(required = true)
protected String propertyOne;
@XmlElement(required = true)
protected String propertyTwo;
@XmlElement(required = true)
protected ObjectB objectB;
}
Run Code Online (Sandbox Code Playgroud)
ObjectB类代码如下所示:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "objectB")
public class ObjectB {
@XmlElement(required = true)
protected String propertyA;
@XmlElement(required = true)
protected boolean propertyB;
}
Run Code Online (Sandbox Code Playgroud)
用于解组的代码:
JAXBContext jc = JAXBContext.newInstance(OnjectA.class);
JSONObject obj = new JSONObject(theJsonString);
Configuration config = new Configuration();
MappedNamespaceConvention con = new MappedNamespaceConvention(config);
XMLStreamReader xmlStreamReader = new MappedXMLStreamReader(obj,con);
Unmarshaller unmarshaller = jc.createUnmarshaller();
ObjectA obj = (ObjectA) unmarshaller.unmarshal(xmlStreamReader);
Run Code Online (Sandbox Code Playgroud)
它不会抛出任何异常或警告.会发生什么是ObjectB被实例化,但它的属性都没有设置它们的值,即propertyA为null,propertyB的默认值为false.我一直在努力弄清楚为什么这不起作用.有人可以帮忙吗?
注意: 我是EclipseLink JAXB(MOXy)的负责人,也是JAXB(JSR-222)专家组的成员.
模型上的JAXB映射似乎是正确的.下面是示例代码,其中我使用您在问题中给出的确切模型以及通过EclipseLink MOXy提供的JSON绑定:
演示
package forum16365788;
import java.io.File;
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>(1);
properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
JAXBContext jc = JAXBContext.newInstance(new Class[] {ObjectA.class}, properties);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File json = new File("src/forum16365788/input.json");
ObjectA objectA = (ObjectA) unmarshaller.unmarshal(json);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(objectA, System.out);
}
}
Run Code Online (Sandbox Code Playgroud)
input.json /输出
下面是我使用的JSON.键objectA和objectB应该引用,你的问题中没有这个.
{
"objectA" : {
"propertyOne" : "some val",
"propertyTwo" : "some other val",
"objectB" : {
"propertyA" : "some val",
"propertyB" : true
}
}
}
Run Code Online (Sandbox Code Playgroud)
欲获得更多信息
| 归档时间: |
|
| 查看次数: |
14819 次 |
| 最近记录: |