0

I`m trying to generate JSON with structure like this:

 "rows": [
    {
        "object": {
            "id": "1"
        },
        "values": [
            "111",
            "reg text",
            "11"
        ]
    }
]

and here are the code:

.writeStartObject()        
.writeStartArray("rows")
    .writeStartObject()       //here i can`t name the object
    .write("id", "'1'@1000")
    .writeEnd()
        .writeStartArray()    //here i can`t name the array
            .write("fax")
            .write("646 555-4567")
        .writeEnd()
.writeEnd()
.writeEnd();

When i tried to add object & array headers inside the brackets, i got an exception "Illegal method during JSON generation, not valid in current context IN_ARRAY". How to generate JSON like mine?

1 Answers1

2

This code produces the JSON output in your question:

generator.writeStartObject()
    .writeStartArray("rows")
        .writeStartObject()
            .writeStartObject("object")
                .write("id", "1")
            .writeEnd()
            .writeStartArray("values")
                .write("111")
                .write("reg text")
                .write("11")
            .writeEnd()
        .writeEnd()
    .writeEnd()
.writeEnd();

The first writeStartObject begins the anonymous object that's inside the rows array. The second writeStartObject produces:

"object": {
    [...]
}

With regards to your comments:

.writeStartObject()       //here i can`t name the object

[...]

    .writeStartArray()    //here i can`t name the array

You can't specify a name because both the object and array are values in an array. The key is to enclose both of them in an object, and then both of them can (in fact, must) have a name.

Richard Fearn
  • 25,073
  • 7
  • 56
  • 55