泽西和JSON单元素阵列

时间:2017-07-27 10:15:55

标签: java jaxb jersey jax-rs

我有如下的JSON结构:

{
    Quote : {
        ItemList : {
            Items : [
                {
                },
                {
                }
            ]
        }
    }
}

但是当它返回1项时,它就像下面的那样:

{
    Quote : {
        ItemList : {
            Items : {

            }
        }
    }
}

为了解决这个问题,我已经编写了MyJAXBContextResolver类,如下所示

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class MyJAXBContextResolver implements ContextResolver<JAXBContext>{
    private JAXBContext context;

    private Class[] types = {ItemList.class,Quote.class,Items.class};

    public MyJAXBContextResolver() throws Exception {
        this.context = new JSONJAXBContext(JSONConfiguration.mapped().arrays("Items").build(),
        types);
    }

    public JAXBContext getContext(Class objectType) {
        for (Class type : types) {
            if (type == objectType) {
                return context;
            }
        }
        return null;
    }     
}

我在web.xml中有必要的配置,意味着我给出的包和加载启动值。所以加载了这个类但是对getContext()的调用没有进行。

需要帮助。

1 个答案:

答案 0 :(得分:0)

You can use the following code :

JSONConfiguration config = JSONConfiguration.natural().build();
JAXBContext ctx = new JSONJAXBContext(config, object.getClass());
StringWriter writer = new StringWriter();
Marshaller u = ctx.createMarshaller();
JSONMarshaller jsonMarshaller = JSONJAXBContext.getJSONMarshaller(u, ctx);
jsonMarshaller.setProperty(Marshaller.JAXB_ENCODING , "UTF-8");
jsonMarshaller.marshallToJSON(object, writer);
result = writer.toString();