SSpoke
SSpoke

Reputation: 5834

Java Minimal Json how to nest multiple arrays in one object?

I'm trying to use this library in my java project https://github.com/ralfstx/minimal-json

Here is how it's used to create objects and arrays.

JsonObject jsonObject = new JsonObject().add( "name", "John" ).add( "age", 23 );
// -> { "name": "John", "age", 23 }

JsonArray jsonArray = new JsonArray().add( "John" ).add( 23 );
// -> [ "John", 23 ]

I'm trying to create something like this

{"start":1234,"end":4321,"time":1000,"cmds":[["String",123],["String2",0],["String3",99999]]};

Here is what I tried it didn't compile

JsonObject jsonObject = new JsonObject().add("start", 1234).add("end", 848383).add("cmds", new JsonArray().add("test").add(1234), new JsonArray().add("test2").add(9594), new JsonArray().add("test6").add("down"));
System.out.println(jsonObject);

This compiles below compiles fine. But it keeps it all as one Array.

JsonObject jsonObject = new JsonObject().add("start", 1234).add("end", 848383).add("time", 1000).add("cmds", new JsonArray().add("test").add(1234).add("test2").add(9594).add("test6").add("down"));
System.out.println(jsonObject);


{"start":1234,"end":848383,"time":1000,"cmds":["test",1234,"test2",9594,"test6","down"]}

Upvotes: 0

Views: 541

Answers (1)

fge
fge

Reputation: 121760

Instead of:

new JsonArray().add("test").add(1234)
    .add("test2").add(9594)
    .add("test6").add("down")

which creates one array of 6 elements, you should:

// new array,
new JsonArray()
    // add a new 2-element array in it,
    .add(new JsonArray().add("test").add(1234))
    // add a new 2-element array in it,
    .add(new JsonArray().add("test2").add(9594))
    // add a new 2-element array in it
    .add(new JsonArray().add("test6").add("down"))

Upvotes: 1

Related Questions