如何编写没有属性名称的JSON值

时间:2014-03-12 23:01:03

标签: java json jackson

我需要创建一些没有属性名称的JSON输出。这是在浏览器中发送到DataTables(datatables.net),DataTables期望JSON这样:

{
    "aaData": [
        [
            "Trident",
            "Internet Explorer 4.0",
            "Win 95+",
            "4",
            "X"
        ],
        [
            "Trident",
            "Internet Explorer 5.0",
            "Win 95+",
            "5",
            "C"
        ]
    ]
}

(来自here的示例。向下滚动到“服务器响应”。)

因为我的数据不是来自已知类,所以我通过在内存中创建树然后调用rootNode.toString()来编写数据:

public String jsonTest()
{
    final JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
    ObjectNode rootNode = nodeFactory.objectNode();

    ArrayNode arrayNode = nodeFactory.arrayNode();
    rootNode.put("aaData", arrayNode);

    for (int i = 0; i < 3; i++) {
        ObjectNode dataNode = nodeFactory.objectNode();
        arrayNode.add(dataNode);
        dataNode.put("field1", "Trident");
        dataNode.put("field2", "Internet Explorer 4.0");
        dataNode.put("field3", "Win 95+");
        dataNode.put("field4", "4");
        dataNode.put("field5", "X");
    }

    return rootNode.toString();
}

这会产生:

{
    "aaData": [
        {
            "field1": "Trident",
            "field2": "Internet Explorer 4.0",
            "field3": "Win 95+",
            "field4": "4",
            "field5": "X"
        },
        {
            "field1": "Trident",
            "field2": "Internet Explorer 4.0",
            "field3": "Win 95+",
            "field4": "4",
            "field5": "X"
        },
        {
            "field1": "Trident",
            "field2": "Internet Explorer 4.0",
            "field3": "Win 95+",
            "field4": "4",
            "field5": "X"
        }
    ] 
}

我的问题:如何完全抑制“field1”,“field2”等,以便我得到json数据表所期望的(如上所示)?

1 个答案:

答案 0 :(得分:2)

你不应该创建一个数组节点而不是一个对象节点吗?

public String jsonTest()
{
    final JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
    ObjectNode rootNode = nodeFactory.objectNode();

    ArrayNode arrayNode = nodeFactory.arrayNode();
    rootNode.put("aaData", arrayNode);

    for (int i = 0; i < 3; i++) {
        ArrayNode dataNode = nodeFactory.arrayNode();
        arrayNode.add(dataNode);
        dataNode.add("Trident");
        dataNode.add("Internet Explorer 4.0");
        dataNode.add("Win 95+");
        dataNode.add("4");
        dataNode.add("X");
    }

    return rootNode.toString();
}