java – 数组上的JAXB JSON强制括号

我试图在仅包含一个元素的列表上强制使用括号.

我想要这样的东西:
{“id”:“0”,“industries”:[{“id”:“0”,“name”:“Technologies”}],“name”:“Google Inc.”}

但我得到:
{“id”:“0”,“industries”:{“id”:“0”,“name”:“Technologies”},“name”:“Google Inc.”}

这是我的实体:

@Entity
@XmlRootElement
public class Company {
 private int id;

 private String name;
 private String description;

 @XMLElement(name="industries")
 private List<Industry> industryList;

    [...]

最后,我的JAXB Context Resolver:

public JAXBContextResolver() throws Exception {

MappedBuilder builder = JSONConfiguration.mapped();
  builder.arrays( “工业”);
  builder.rootUnwrapping(真);

this.context = new JSONJAXBContext(builder.build(),Company.class);
 }

最佳答案 谢谢你的帮助,但我找到了答案.实际上,您需要指定一个JAXBContextResolver,它指定自然的JSON配置.您需要提供需要转换为JSON的每个容器的类型列表.在此示例中,您可以看到我指定了GetCompanyResponse,它是Company的容器.

@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
    private JAXBContext context;
    private Class[] types = { GetCompanyResponse.class };

    public JAXBContextResolver() throws Exception {
        this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), types);
    }

    public JAXBContext getContext(Class<?> objectType) {
        for (Class clazz : types) {
            if (clazz.equals(objectType)) {
                return context;
            }
        }

        return null;
    }
}
点赞