diff --git a/guides/json.md b/guides/json.md new file mode 100644 index 000000000..20a91818b --- /dev/null +++ b/guides/json.md @@ -0,0 +1,59 @@ +- [Working with Json](#working-with-json) + - [Serialization](#serialization) + - [Using toJsonString method](#using-tojsonstring-method) + - [Manual serialization](#manually-serialize-by-providing-mapper-and-generator) + + +# Working with Json + +OpenSearch Java client seamlessly integrate with JSON providing serialization and deserialization capability. + +## Serialization + +For demonstration let's consider an instance of `SearchRequest`. + +```java +public static void main(final String[] args) { + SearchRequest searchRequest = SearchRequest.of( + request -> request.index("index1", "index2") + .aggregations(Collections.emptyMap()) + .terminateAfter(5L) + .query(q -> q.match(t -> t.field("name").query(FieldValue.of("OpenSearch")))) + ); +} + +``` +### Using toJsonString method +For classes implementing `PlainJsonSerializable`, which extends `JsonpSerializable`, a default `toJsonString` method is provided. +This method utilizes the default mapper and generator from the JsonpUtils class within the package to streamline the serialization process. + +The following code example demonstrates how to use the `toJsonString` method to serialize objects: + +```java +String requestString = searchRequest.toJsonString(); +``` + + +### Manually serialize by providing mapper and generator +For classes implementing the `JsonpSerializable` interface, a serialize method is provided, which takes a mapper and a generator +as arguments and returns the JSON string representation of the instance. + +The following sample code demonstrates how to serialize an instance of a Java class: + +```java +private String toJson(JsonpSerializable object) { + try (StringWriter writer = new StringWriter()) { + JsonbJsonpMapper mapper = new JsonbJsonpMapper(); + try (JsonGenerator generator = mapper.jsonProvider().createGenerator(writer)) { + serialize(generator, mapper); + } + return writer.toString(); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } +} + +``` + + +