我正在开发一个使用 Jersey 将对象转换为 JSON 的项目。我希望能够写出嵌套列表,如下所示:
{"data":[["one", "two", "three"], ["a", "b", "c"]]}
我想首先将数据转换为 <LinkedList<LinkedList<String>>> 的对象,我认为 Jersey 会做正确的事情。以上是作为空值列表输出的:
{"data":[null, null]}
在阅读了需要包装嵌套对象之后,我尝试了以下操作:
@XmlRootElement(name = "foo")
@XmlType(propOrder = {"data"})
public class Foo
{
private Collection<FooData> data = new LinkedList<FooData>();
@XmlElement(name = "data")
public Collection<FooData> getData()
{
return data;
}
public void addData(Collection data)
{
FooData d = new FooData();
for(Object o: data)
{
d.getData().add(o == null ? (String)o : o.toString());
}
this.data.add(d);
}
@XmlRootElement(name = "FooData")
public static class FooData
{
private Collection<String> data = new LinkedList<String>();
@XmlElement
public Collection<String> getData()
{
return data;
}
}
}
该代码输出以下内容,更接近我想要的内容:
{"data":[{"data":["one", "two", "three"]},{"data":["a", "b", "c"]}]}
我希望第一个数据是列表列表,而不是单元素字典列表。我如何实现这一目标?
这是我的 JAXBContentResolver:
@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext>
{
private JAXBContext context;
private Set<Class<?>> types;
// Only parent classes are required here. Nested classes are implicit.
protected Class<?>[] classTypes = new Class[] {Foo.class};
protected Set<String> jsonArray = new HashSet<String>(1) {
{
add("data");
}
};
public JAXBContextResolver() throws Exception
{
Map<String, Object> props = new HashMap<String, Object>();
props.put(JSONJAXBContext.JSON_NOTATION, JSONJAXBContext.JSONNotation.MAPPED);
props.put(JSONJAXBContext.JSON_ROOT_UNWRAPPING, Boolean.TRUE);
props.put(JSONJAXBContext.JSON_ARRAYS, jsonArray);
this.types = new HashSet<Class<?>>(Arrays.asList(classTypes));
this.context = new JSONJAXBContext(classTyes, props);
}
public JAXBContext getContext(Class<?> objectType)
{
return (types.contains(objectType)) ? context : null;
}
}