gpt4 book ai didi

json - 从 json 解码嵌套对象

转载 作者:行者123 更新时间:2023-12-02 07:03:34 25 4
gpt4 key购买 nike

我有传入的 JSON 字符串,我需要解码为 JAXB 注释对象。我正在使用 jettison 来做到这一点。 JSON 字符串如下所示:

{ 
objectA :
{
"propertyOne" : "some val",
"propertyTwo" : "some other val",
objectB :
{
"propertyA" : "some val",
"propertyB" : "true"
}
}
}

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;
}

ObjectB 类代码如下所示:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "objectB")
public class ObjectB {
@XmlElement(required = true)
protected String propertyA;
@XmlElement(required = true)
protected boolean propertyB;
}

用于解码的代码:

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);

它不会抛出任何异常或警告。发生的情况是 ObjectB 已实例化,但其属性均未设置值,即 propertyA 为 null,而 propertyB 的默认值为 false。我一直在努力弄清楚为什么这不起作用。有人可以帮忙吗?

最佳答案

注意:我是 EclipseLink JAXB (MOXy) JAXB (JSR-222) 的领导和成员专家组。

您模型上的 JAXB 映射似乎是正确的。下面是示例代码,其中我使用了您在问题中给出的确切模型以及通过 EclipseLink MOXy 提供的 JSON 绑定(bind):

演示

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);
}

}

input.json/输出

下面是我使用的 JSON。键 objectAobjectB 应该被引用,你的问题中没有这个。

{
"objectA" : {
"propertyOne" : "some val",
"propertyTwo" : "some other val",
"objectB" : {
"propertyA" : "some val",
"propertyB" : true
}
}
}

了解更多信息

关于json - 从 json 解码嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16365788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com