ricb
ricb

Reputation: 1217

How to write JSON value with no property name

I need to create some JSON output without property names. This is to send to DataTables (datatables.net) in the browser, and DataTables expects JSON that like this:

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

(Sample from here. Scroll down to "server response.")

Because my data is not coming from a known class, I am writing the data by creating a tree in memory and then calling 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();
}

This generates:

{
    "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"
        }
    ] 
}

My question: how can I suppress the "field1", "field2", etc., completely, so that I get the json datatables is expecting (as shown above)?

Upvotes: 2

Views: 3358

Answers (1)

Izaaz Yunus
Izaaz Yunus

Reputation: 2828

Shouldnt you be creating an Array Node instead of an Object Node?

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();
}

Upvotes: 3

Related Questions