我有这门课:
class A {
@XmlElement(name = "bees")
@XmlElementWrapper(name="bee")
public List<B> bees;
}
我的 XML 看起来像这样:
<a>
<bees>
<bee>...</bee>
<bee>...</bee>
</bees>
</a>
但是当通过 JSON 使用时:
{
"bees": {
"bee": [
....
]
}
}
我需要:
{
"bees": {
"bee": { .. }, "bee": { .. }, ..
}
}
有人可以帮忙吗?
最佳答案
注意:我是EclipseLink JAXB (MOXy) JAXB (JSR-222) 的领导者和成员专家组。
而不是:
{
"bees": {
"bee": { .. },
"bee": { .. },
..
}
}
我会推荐以下内容:
{
"bees" : [
{ .. },
{ .. },
..
} ]
}
下面是如何使用 MOXy 根据您的映射生成此 JSON:
import java.util.*;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
import org.eclipse.persistence.jaxb.MarshallerProperties;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
properties.put(JAXBContextProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
JAXBContext jc = JAXBContext.newInstance(new Class[] {A.class}, properties);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource xml = new StreamSource("src/forum19560166/input.xml");
A a = unmarshaller.unmarshal(xml, A.class).getValue();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
marshaller.marshal(a, System.out);
}
}
了解更多信息
关于java - XML 包装器 JSON 格式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19560166/