Skip to content

Commit f154afd

Browse files
author
Chris Cho
committed
PR review fixes
1 parent 7bdd38e commit f154afd

File tree

1 file changed

+118
-68
lines changed

1 file changed

+118
-68
lines changed

source/fundamentals/data-formats/document-data-format-extended-json.txt

Lines changed: 118 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -14,26 +14,31 @@ Document Data Format: Extended JSON
1414
Overview
1515
--------
1616

17-
JSON is a data format that encodes the values of objects, arrays, numbers, and
18-
so on. The **Extended JSON** format adds special syntax to JSON objects to
19-
represent field type information that directly corresponds to each type in
20-
BSON, the format that MongoDB uses to store data.
17+
JSON is a data format that represents the values of objects, arrays, numbers,
18+
strings, booleans, and nulls. The **Extended JSON** format defines a reserved
19+
set of keys prefixed with "``$``" to represent field type information that
20+
directly corresponds to each type in BSON, the format that MongoDB uses to
21+
store data.
2122

2223
This guide explains the following topics:
2324

2425
- the different MongoDB Extended JSON formats
2526
- how to use the BSON library to convert between Extended JSON and Java objects
27+
- how to create a custom conversion of BSON types
2628

2729
For more information on the difference between these formats, see our
2830
`article on JSON and BSON <https://www.mongodb.com/json-and-bson>`__.
2931

3032
Extended JSON Formats
3133
---------------------
3234

33-
MongoDB Extended JSON represents BSON in different formats to handle
34-
specific use cases. These formats differ in the level of prioritization in
35-
preserving BSON type information and how closely they resemble ordinary,
36-
human-readable JSON.
35+
MongoDB Extended JSON features different string formats to represent BSON data.
36+
Each of the different formats conform to the `JSON RFC <https://tools.ietf.org/html/rfc7159>`__
37+
and meet specific use cases. The **extended** format, also known as the
38+
**canonical** format, features specific representations for every BSON type
39+
for bidirectional conversion without loss of information. The **relaxed**
40+
format is more concise and closer to ordinary JSON, but does not represent
41+
all the type information such as specific byte size of number fields.
3742

3843
See the table below to see a description of each format:
3944

@@ -63,11 +68,10 @@ See the table below to see a description of each format:
6368
|
6469
| For more information on this format, see the server manual page on :manual:`Data Types in the mongo shell </core/shell-types/>`.
6570

66-
* - **Strict**
67-
- | Deprecated. This representation is the legacy format that fully conforms to the `JSON RFC <http://www.json.org/>`__ which allows any JSON parser to read the type information.
68-
| This format prioritizes for compatibility at the loss of certain type information introduced in newer versions of BSON.
69-
|
70-
| For more information on this format, see the server manual page on :manual:`Extended JSON (v1) </reference/mongodb-extended-json-v1/>`.
71+
.. _extended_json_example_section:
72+
73+
For more detailed information on these formats, see the
74+
`Extended JSON specification <https://github.com/mongodb/specifications/blob/master/source/extended-json.rst>`__.
7175

7276
Extended JSON Examples
7377
~~~~~~~~~~~~~~~~~~~~~~
@@ -111,26 +115,47 @@ corresponds to the format of the example you want to see:
111115
"numViews": NumberLong("36520312")
112116
}
113117

114-
.. tab:: Strict
115-
:tabid: strict-format
116-
117-
.. code-block:: json
118-
119-
{
120-
"_id": { "$oid": "573a1391f29313caabcd9637" },
121-
"createdAt": { "$date": "2020-09-30T18:22:51.648Z" },
122-
"numViews": { "$numberLong": "36520312" }
123-
}
124-
125118

126119
Read Extended JSON
127120
------------------
128121

129122
You can read an Extended JSON string into Java objects with the BSON library
130-
by using an instance of the :java-docs:`JsonReader </apidocs/bson/org/bson/json/JsonReader.html>`
131-
class. This class contains methods to sequentially parse the fields and values
132-
in the Extended JSON object, and returns them as Java objects. The
133-
``JsonReader`` class automatically handles any of the Extended JSON formats.
123+
by calling the ``parse()`` static method from either the ``Document`` or
124+
``BsonDocument`` class, depending on which object type you need. This method
125+
parses the Extended JSON string in any of the formats and returns an instance
126+
of that class containing the data.
127+
128+
The following example shows how you can use the ``Document`` class to read
129+
an example Extended JSON string into a ``Document`` object using the
130+
``parse()`` method:
131+
132+
.. code-block:: java
133+
134+
String ejsonStr = "{ \"_id\": { \"$oid\": \"507f1f77bcf86cd799439011\"}," +
135+
"\"myNumber\": {\"$numberLong\": \"4794261\" }}}";
136+
137+
Document doc = new Document(Document.parse(ejsonStr));
138+
System.out.println(doc);
139+
140+
The output of the code above resembles the following:
141+
142+
.. code-block:: none
143+
:copyable: False
144+
145+
Document{{_id=507f1f77bcf86cd799439011, myNumber=4794261}}
146+
147+
For more information on the driver document classes, see our Fundamentals page
148+
on :doc:`Documents </fundamentals/data-formats/documents>`.
149+
150+
Read Extended JSON using the BSON Library
151+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
152+
153+
You can also read an Extended JSON string into Java objects without using
154+
the MongoDB driver's document classes by using the
155+
:java-docs:`JsonReader </apidocs/bson/org/bson/json/JsonReader.html>` class.
156+
This class contains methods to sequentially parse the fields and values
157+
in any format of the Extended JSON string, and returns them as Java objects.
158+
MongoDB driver's document classes also use this class to parse Extended JSON.
134159

135160
The following code example shows how you can use ``JsonReader`` to convert
136161
an Extended JSON string into Java objects:
@@ -164,47 +189,46 @@ The output of this code example resembles the following:
164189
507f1f77bcf86cd799439011 is type: org.bson.types.ObjectId
165190
4794261 is type: java.lang.Long
166191

167-
To construct an instance of a ``Document`` from Extended JSON, you can call
168-
the ``parse()`` static factory method of the ``Document`` or ``BsonDocument``
169-
class. This method instantiates a ``JsonReader``, parses the Extended JSON
170-
string, and returns an instance of that class containing the data.
171192

172-
The following example shows how you can use the ``Document`` class to read
173-
the same example Extended JSON string into a ``Document`` object using the
174-
``parse()`` method:
193+
For additional information on the classes and methods mentioned on this
194+
section, see the following API documentation:
175195

176-
.. code-block:: java
196+
Write Extended JSON
197+
-------------------
177198

178-
String ejsonStr = "{ \"_id\": { \"$oid\": \"507f1f77bcf86cd799439011\"}," +
179-
"\"myNumber\": {\"$numberLong\": \"4794261\" }}}";
199+
You can write an Extended JSON string from an instance of ``Document`` or
200+
``BsonDocument`` by calling the ``toJson()`` method, passing it an instance of
201+
``JsonWriterSettings`` to specify the Extended JSON format.
180202

181-
Document doc = new Document(Document.parse(ejsonStr));
182-
System.out.println(doc);
203+
In this example, we output the Extended JSON in the "Shell" format.
183204

184-
The output of the code above resembles the following:
205+
.. code-block:: java
185206

186-
.. code-block:: none
187-
:copyable: False
207+
Document myDoc = new Document();
208+
myDoc.append("_id", new ObjectId("507f1f77bcf86cd799439012")).append("myNumber", 11223344);
188209

189-
Document{{_id=507f1f77bcf86cd799439011, myNumber=4794261}}
210+
JsonWriterSettings settings = JsonWriterSettings.builder().outputMode(JsonMode.SHELL).build();
211+
System.out.println(doc.toJson(settings));
190212

191-
For more information on the driver document classes, see our Fundamentals page
192-
on :doc:`Documents </fundamentals/data-formats/documents>`.
213+
The output of this code example resembles the following:
193214

194-
For additional information on the classes and methods mentioned on this
195-
section, see the following API documentation:
215+
.. code-block:: none
216+
:copyable: false
196217

197-
Write Extended JSON
198-
-------------------
218+
{"_id": ObjectId("507f1f77bcf86cd799439011"), "myNumber": NumberLong(4794261)}
219+
220+
Write Extended JSON using the BSON Library
221+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
199222

200-
You can convert Java objects into Extended JSON with the BSON library by using
201-
the :java-docs:`JsonWriter </apidocs/bson/org/bson/json/JsonWriter.html>`
202-
class. To construct an instance of ``JsonWriter``, pass a
203-
subclass of a Java ``Writer`` to specify how you want to output the Extended
204-
JSON. You can optionally pass a :java-docs:`JsonWriterSettings </apidocs/bson/org/bson/json/JsonWriterSettings.html>`
223+
You can also read an Extended JSON string into Java objects without using
224+
the MongoDB driver's document classes by using the
225+
:java-docs:`JsonWriter </apidocs/bson/org/bson/json/JsonWriter.html>` class.
226+
To construct an instance of ``JsonWriter``, pass a subclass of a Java
227+
``Writer`` to specify how you want to output the Extended JSON. You can
228+
optionally pass a :java-docs:`JsonWriterSettings </apidocs/bson/org/bson/json/JsonWriterSettings.html>`
205229
instance to specify options such as the Extended JSON format. By default, the
206-
``JsonWriter`` uses the "Strict" Extended JSON format to guarantee backwards
207-
compatibility.
230+
``JsonWriter`` uses the "Relaxed" Extended JSON format. MongoDB driver's
231+
document classes also use this class to convert BSON to Extended JSON.
208232

209233
The following code example shows how you can use ``JsonWriter`` to create an
210234
Extended JSON string and output it to ``System.out``. We specify the format
@@ -230,21 +254,47 @@ The output of this code example resembles the following:
230254

231255
{"_id": {"$oid": "507f1f77bcf86cd799439012"}, "myNumber": {"$numberLong": "11223344"}}
232256

233-
To write Extended JSON from an instance of a ``Document``, you can call the
234-
``toJson()`` method, passing it an instance of ``JsonWriterSettings`` to
235-
specify the Extended JSON format. In this example, we use the "Shell" format.
257+
258+
Custom BSON Type Conversion
259+
---------------------------
260+
261+
In addition to specifying the ``outputMode()`` to format the JSON output, you
262+
can further customize the output by adding converters to your
263+
``JsonWriterSettings.Builder``. These converter methods detect the Java types
264+
and execute the logic defined by the :java-docs:`Converter </apidocs/bson/org/bson/json/Converter.html>`
265+
passed to them. For a full list of converter methods, see the
266+
:java-docs:`API documentation </apidocs/bson/org/bson/json/JsonWriterSettings.Builder.html>`.
267+
268+
The following sample code shows how to append converters, defined as lambda
269+
expressions, to simplify the "Relaxed" JSON output.
236270

237271
.. code-block:: java
238272

239-
Document myDoc = new Document();
240-
myDoc.append("_id", new ObjectId("507f1f77bcf86cd799439012")).append("myNumber", 11223344);
273+
JsonWriterSettings settings = JsonWriterSettings.builder().outputMode(JsonMode.RELAXED)
274+
.objectIdConverter((value, writer) -> writer.writeString(value.toHexString()))
275+
.dateTimeConverter(
276+
(value, writer) -> {
277+
ZonedDateTime zonedDateTime = Instant.ofEpochMilli(value).atZone(ZoneOffset.UTC);
278+
writer.writeString(DateTimeFormatter.ISO_DATE_TIME.format(zonedDateTime));
279+
})
280+
.build();
241281

242-
JsonWriterSettings settings = JsonWriterSettings.builder().outputMode(JsonMode.SHELL).build();
243-
System.out.println(doc.toJson(settings));
282+
Document doc = new Document()
283+
.append("_id", new ObjectId("507f1f77bcf86cd799439012"))
284+
.append("createdAt", Date.from(Instant.ofEpochMilli(1601499609000L)))
285+
.append("myNumber", 4794261);
244286

245-
The output of this code example resembles the following:
287+
System.out.println(doc.toJson(settings)));
246288

247-
.. code-block:: none
248-
:copyable: false
289+
The output of this code should resemble the following:
249290

250-
{"_id": ObjectId("507f1f77bcf86cd799439011"), "myNumber": NumberLong(4794261)}
291+
.. code-block:: json
292+
293+
{"_id": "507f1f77bcf86cd799439012", "createdAt": "2020-09-30T21:00:09Z", "myNumber": 4794261}
294+
295+
Without specifying the converters, the "Relaxed" JSON output resembles the
296+
following:
297+
298+
.. code-block:: json
299+
300+
{"_id": {"$oid": "507f1f77bcf86cd799439012"}, "createdAt": {"$date": "2020-09-30T21:00:09Z"}, "myNumber": 4794261}

0 commit comments

Comments
 (0)