I have a file in json format, is there a way to convert it to a XContentBuilder?
What I want to do is to read a file with some mapping and then convert it to XContentBuilder
Something like:
XContentBuilder builder = JsonXContent.contentBuilder().source(String json);
Usually the API should accept a String
or byte[]
so you shouldn't need to convert. Maybe you want CreateIndexRequestBuilder#addMapping(String, String)
?
If you really, really, really want an XContentBuilder
you can make an XContentParser
and copy the contents to a builder. As of Elasticsearch 5.2 this should do it:
String message = "{\"test\":\"test\"}";
XContentBuilder b = XContentFactory.jsonBuilder().prettyPrint();
try (XContentParser p = XContentFactory.xContent(XContentType.JSON).createParser(NamedXContentRegistry.EMPTY, message)) {
b.copyCurrentStructure(p);
}
System.err.println(b.string());
You could probably also do something with raw but I don't think that is worth it.
Pre 5.2 you don't need the NamedXContentRegistry.EMPTY,
part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With