加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

数组 – 如何强制抛出写数组,即使数组中只有一个元素?

发布时间:2020-12-16 08:00:25 所属栏目:百科 来源:网络整理
导读:简单的例子如下: 我按预期得到以下内容: {"person":{"name":"john","tags":["tag1","tag2"]}} 但是,如果我只设置一个标签,我得到: {"person":{"name":"john","tags":"tag1"}} 我期待得到这个: {"person":{"name":"john","tags":["tag1"]}} 也就是说,j
简单的例子如下:

我按预期得到以下内容:

{"person":{"name":"john","tags":["tag1","tag2"]}}

但是,如果我只设置一个标签,我得到:

{"person":{"name":"john","tags":"tag1"}}

我期待得到这个:

{"person":{"name":"john","tags":["tag1"]}}

也就是说,jettison已经删除了数组的标签,因为数组中只有一个元素。

我觉得这很不安全。

如何强制抛出写数组,即使只有一个元素?

注意:我知道还有其他替代品,例如StAXON。
但是,在这里我问如何使用Jettison来实现这一点。
请不要建议另一种替代方案。

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.*;

import java.io.*;
import javax.xml.bind.*;
import javax.xml.stream.XMLStreamWriter;
import org.codehaus.jettison.mapped.*;


public class JettisonTest {
    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Person.class);

        Person person = new Person();
        person.name = "john";
        person.tags.add("tag1");
        person.tags.add("tag2");

        Configuration config = new Configuration();
        MappedNamespaceConvention con = new MappedNamespaceConvention(config);
        Writer writer = new OutputStreamWriter(System.out);
        XMLStreamWriter xmlStreamWriter = new MappedXMLStreamWriter(con,writer);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.marshal(person,xmlStreamWriter);
    }
}

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class Person {
    String name;
    List<String> tags = new ArrayList<String>();
}
我发现这个: https://blogs.oracle.com/japod/entry/missing_brackets_at_json_one

似乎在你的上下文解析器中添加一行以明确地声明该标签是一个数组是这样做的方式;即

props.put(JSONJAXBContext.JSON_ARRAYS,"["tags"]");

注意:我不熟悉Jettison,所以没有个人经验来支持这一点。只有上面博客上的信息。

@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {

    private JAXBContext context;
    private Class[] types = {ArrayWrapper.class};

    public JAXBContextResolver() throws Exception {
        Map props = new HashMap<String,Object>();
        props.put(JSONJAXBContext.JSON_NOTATION,"MAPPED");
        props.put(JSONJAXBContext.JSON_ROOT_UNWRAPPING,Boolean.TRUE);

        props.put(JSONJAXBContext.JSON_ARRAYS,"["tags"]"); //STATE WHICH ELEMENT IS AN ARRAY

        this.context = new JSONJAXBContext(types,props);
    }

    public JAXBContext getContext(Class<?> objectType) {
        return (types[0].equals(objectType)) ? context : null;
    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读