Insert nested JSON with XContentBuilder

I have data flowing into a document from two sources. One is text which needs to be converted to JSON. Simple to add it using:

jsonBuilder.field(name, value);

The other source has data that is already formatted as JSON.

String nestedExample = "{\"Details\": [ {\"Login\":\"ABC\", \"DateTime\": 123213113},{\"Login\":\"BCD\", \"DateTime\": 123213213}, {\"Login\":\"EFG\", \"DateTime\": 123213413}]}";

I found that I could use jsonBuilder,rawField to insert prebuilt JSON, however it always wants a field name.If I use:

InputStream jsonStream = new ByteArrayInputStream(nestedExample.getBytes());
jsonBuilder.rawField(name, jsonStream);

It creates an additional field name which creates an additional layer of nesting to my data structure.

I cannot find a way to insert this raw data that doesnt require me to specify a field name, which creates an additional layer of nesting that I do not want.

I have also tried using XContentParser and then copyCurrentStructure, but that also needs a field name and again creates an additioanl layer of nesting.

I'm sure this is really simple, but how can I insert raw JSON into a document field using XContentBuilder?

Thanks!

I think using copyCurrentStructure(XContentParser) is the way to go here. Here's some example code:

XContentBuilder builder = JsonXContent.contentBuilder().prettyPrint();
        String nestedExample = "{\"foo\": {\"bar\":\"baz\"}}";
        XContentParser parser = JsonXContent.jsonXContent
                .createParser(NamedXContentRegistry.EMPTY, nestedExample);
        builder.startObject();
        builder.startArray("name");
        builder.copyCurrentStructure(parser);
        builder.endArray();
        builder.endObject();
        System.out.println(builder.bytes().utf8ToString());

prints

{
  "name" : [
    {
      "foo" : {
        "bar" : "baz"
      }
    }
  ]
}

and if you need the nested object as a field value you can do:

...
builder.field("name");
builder.copyCurrentStructure(parser);
...
1 Like

Thanks for the response!

It is the field called "name" in your example that I am trying to avoid. Is there a way that I can use the field "foo" in your example as the field name (basically telling XcontentBuilder, here is a JSON object to insert and you should take the existing field name from that) without having to specify another one.

Also, XcontentParser only seems to return me the first object in an array. How can I get to the other values, when I supply an array of objects?

Thanks!

I got this working now! Thank you. I hadn't realised that it was possible to just call jsonBuilder.field(name) and then to do the copyCurrrentStructure(exampleString) immediately after. This solved it for me!

Thank you!

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.