• Home
  • Raw
  • Download

Lines Matching full:json

3 # JSON features
6 …pter, we'll walk through features of [JSON](https://www.json.org/json-en.html) serialization avail…
12 * [Json configuration](#json-configuration)
16 * [Alternative Json names](#alternative-json-names)
26 * [Json elements](#json-elements)
27 * [Parsing to Json element](#parsing-to-json-element)
28 * [Types of Json elements](#types-of-json-elements)
29 * [Json element builders](#json-element-builders)
30 * [Decoding Json elements](#decoding-json-elements)
31 * [Encoding literal Json content (experimental)](#encoding-literal-json-content-experimental)
34 * [Json transformations](#json-transformations)
40 * [Maintaining custom JSON attributes](#maintaining-custom-json-attributes)
44 ## Json configuration
46 The default [Json] implementation is quite strict with respect to invalid inputs. It enforces Kotli…
47 restricts Kotlin values that can be serialized so that the resulting JSON representations are stand…
48 Many non-standard JSON features are supported by creating a custom instance of a JSON _format_.
50 To use a custom JSON format configuration, create your own [Json] class instance from an existing
51 instance, such as a default `Json` object, using the [Json()] builder function. Specify parameter v…
52 in the parentheses via the [JsonBuilder] DSL. The resulting `Json` format instance is immutable and…
58 This chapter shows configuration features that [Json] supports.
60 <!--- INCLUDE .*-json-.*
62 import kotlinx.serialization.json.*
67 By default, the [Json] output is a single line. You can configure it to pretty print the output (th…
71 val format = Json { prettyPrint = true }
82 > You can get the full code [here](../guide/example/example-json-01.kt).
97 By default, [Json] parser enforces various JSON restrictions to be as specification-compliant as po…
102 val format = Json { isLenient = true }
121 > You can get the full code [here](../guide/example/example-json-02.kt).
123 You get the object, even though all keys of the source JSON, string, and enum values are unquoted, …
134 JSON format is often used to read the output of third-party services or in other dynamic environmen…
140 val format = Json { ignoreUnknownKeys = true }
153 > You can get the full code [here](../guide/example/example-json-03.kt).
163 ### Alternative Json names
165 It's not a rare case when JSON fields are renamed due to a schema version change.
166 …ialName` annotation](basic-serialization.md#serial-field-names) to change the name of a JSON field,
168 To support multiple JSON names for the one Kotlin property, there is the [JsonNames] annotation:
175 val project = Json.decodeFromString<Project>("""{"name":"kotlinx.serialization"}""")
177 val oldProject = Json.decodeFromString<Project>("""{"title":"kotlinx.coroutines"}""")
182 > You can get the full code [here](../guide/example/example-json-04.kt).
184 As you can see, both `name` and `title` Json fields correspond to `name` property:
199 JSON formats that from third parties can evolve, sometimes changing the field types.
201 The default [Json] implementation is strict with respect to input types as was demonstrated in
212 > This list may be expanded in the future, so that [Json] instance configured with this property be…
218 val format = Json { coerceInputValues = true }
231 > You can get the full code [here](../guide/example/example-json-05.kt).
250 val format = Json { encodeDefaults = true }
265 > You can get the full code [here](../guide/example/example-json-06.kt).
277 By default, all `null` values are encoded into JSON strings, but in some cases you may want to omit…
280 If you set property to `false`, fields with `null` values are not encoded into JSON even if the pro…
281 default `null` value. When decoding such JSON, the absence of a property value is treated as `null`…
285 val format = Json { explicitNulls = false }
298 val json = format.encodeToString(data)
299 println(json)
300 println(format.decodeFromString<Project>(json))
304 > You can get the full code [here](../guide/example/example-json-07.kt).
306 As you can see, `version`, `website` and `description` fields are not present in output JSON on the…
321 JSON format does not natively support the concept of a map with structured keys. Keys in JSON objec…
329 val format = Json { allowStructuredMapKeys = true }
343 > You can get the full code [here](../guide/example/example-json-08.kt).
345 The map with structured keys gets represented as JSON array with the following items: `[key1, value…
355 …t, special floating-point values like [Double.NaN] and infinities are not supported in JSON because
356 the JSON specification prohibits it.
361 val format = Json { allowSpecialFloatingPointValues = true }
374 > You can get the full code [here](../guide/example/example-json-09.kt).
376 This example produces the following non-stardard JSON output, yet it is a widely used encoding for
391 val format = Json { classDiscriminator = "#class" }
408 > You can get the full code [here](../guide/example/example-json-10.kt).
411 control over the resulting JSON object:
419 …cify different class discriminators for different hierarchies. Instead of Json instance property, …
438 Discriminator specified in the annotation has priority over discriminator in Json configuration:
456 val format = Json { classDiscriminator = "#class" }
464 > You can get the full code [here](../guide/example/example-json-11.kt).
484 val format = Json { classDiscriminatorMode = ClassDiscriminatorMode.NONE }
500 > You can get the full code [here](../guide/example/example-json-12.kt).
517 [Json] uses exact Kotlin enum values names for decoding by default.
522 val format = Json { decodeEnumsCaseInsensitive = true }
534 > You can get the full code [here](../guide/example/example-json-13.kt).
548 If properties' names in Json input are different from Kotlin ones, it is recommended to specify the…
552Json] instance. `kotlinx.serialization` provides one strategy implementation out of the box, the […
558 val format = Json { namingStrategy = JsonNamingStrategy.SnakeCase }
566 > You can get the full code [here](../guide/example/example-json-14.kt).
594 ## Json elements
596 Aside from direct conversions between strings and JSON objects, Kotlin serialization offers APIs th…
597 other ways of working with JSON in the code. For example, you might need to tweak the data before i…
603 ### Parsing to Json element
605 A string can be _parsed_ into an instance of [JsonElement] with the [Json.parseToJsonElement] funct…
607 It just parses a JSON and forms an object representing it:
611 val element = Json.parseToJsonElement("""
618 > You can get the full code [here](../guide/example/example-json-15.kt).
620 A `JsonElement` prints itself as a valid JSON:
628 ### Types of Json elements
630 A [JsonElement] class has three direct subtypes, closely following JSON grammar:
632 * [JsonPrimitive] represents primitive JSON elements, such as string, number, boolean, and null.
637 * [JsonArray] represents a JSON `[...]` array. It is a Kotlin [List] of `JsonElement` items.
639 * [JsonObject] represents a JSON `{...}` object. It is a Kotlin [Map] from `String` keys to `JsonEl…
644 and similar ones for other types. This is how you can use them for processing JSON whose structure …
648 val element = Json.parseToJsonElement("""
661 > You can get the full code [here](../guide/example/example-json-16.kt).
673 ### Json element builders
676 [buildJsonArray] and [buildJsonObject]. They provide a DSL to define the resulting JSON structure. …
677 is similar to Kotlin standard library collection builders, but with a JSON-specific convenience
701 > You can get the full code [here](../guide/example/example-json-17.kt).
703 As a result, you get a proper JSON string:
711 ### Decoding Json elements
714 the [Json.decodeFromJsonElement] function:
725 val data = Json.decodeFromJsonElement<Project>(element)
730 > You can get the full code [here](../guide/example/example-json-18.kt).
740 ### Encoding literal Json content (experimental)
749 The JSON specification does not restrict the size or precision of numbers, however it is not possib…
759 val format = Json { prettyPrint = true }
776 > You can get the full code [here](../guide/example/example-json-19.kt).
778 Even though `pi` was defined as a number with 30 decimal places, the resulting JSON does not reflec…
779 …s truncated to 15 decimal places, and the String is wrapped in quotes - which is not a JSON number.
795 val format = Json { prettyPrint = true }
800 // use JsonUnquotedLiteral to encode raw JSON content
816 > You can get the full code [here](../guide/example/example-json-20.kt).
833 [Json Transformations](#json-transformations) below.)
846 val piObject: JsonObject = Json.decodeFromString(piObjectJson)
856 > You can get the full code [here](../guide/example/example-json-21.kt).
858 …act value of `pi` is decoded, with all 30 decimal places of precision that were in the source JSON.
878 > You can get the full code [here](../guide/example/example-json-22.kt).
881 …x.serialization.json.internal.JsonEncodingException: Creating a literal unquoted value of 'null' i…
887 ## Json transformations
889 To affect the shape and contents of JSON output after serialization, or adapt input to deserializat…
893 serializer to a problem of manipulating a Json elements tree.
899 …nteraction with `Encoder` or `Decoder`, this class asks you to supply transformations for JSON tree
905 The first example is an implementation of JSON array wrapping for lists.
907 Consider a REST API that returns a JSON array of `User` objects, or a single object (not wrapped in…
941 Now you can test the code with a JSON array or a single JSON object as inputs.
945 println(Json.decodeFromString<Project>("""
948 println(Json.decodeFromString<Project>("""
954 > You can get the full code [here](../guide/example/example-json-23.kt).
967 …plement the `transformSerialize` function to unwrap a single-element list into a single JSON object
1002 println(Json.encodeToString(data))
1006 > You can get the full code [here](../guide/example/example-json-24.kt).
1008 You end up with a single JSON object, not an array with one element:
1018 Another kind of useful transformation is omitting specific values from the output JSON, for example…
1022 but you need it omitted from the JSON when it is equal to `Kotlin` (we can all agree that Kotlin sh…
1040 pass the above `ProjectSerializer` to [Json.encodeToString] function as was shown in
1046 println(Json.encodeToString(data)) // using plugin-generated serializer
1047 println(Json.encodeToString(ProjectSerializer, data)) // using custom serializer
1051 > You can get the full code [here](../guide/example/example-json-25.kt).
1065 (also known as _class discriminator_) in the incoming JSON object to determine the actual serializer
1069 the actual type by the shape of JSON, for example by the presence of a specific key.
1098 the `owner` key in the JSON object.
1118 val string = Json.encodeToString(ListSerializer(ProjectSerializer), data)
1120 println(Json.decodeFromString(ListSerializer(ProjectSerializer), string))
1124 > You can get the full code [here](../guide/example/example-json-26.kt).
1126 No class discriminator is added in the JSON output:
1142 Here are some useful things about custom serializers with [Json]:
1144 …der] can be cast to [JsonEncoder], and [Decoder] to [JsonDecoder], if the current format is [Json].
1148 * Both [`JsonDecoder`][JsonDecoder.json] and [`JsonEncoder`][JsonEncoder.json] have the `json` prop…
1149 which returns [Json] instance with all settings that are currently in use.
1150 * [Json] has the [encodeToJsonElement][Json.encodeToJsonElement] and [decodeFromJsonElement][Json.d…
1179 require(decoder is JsonDecoder) // this class can be decoded only by Json
1185 return Response.Ok(decoder.json.decodeFromJsonElement(dataSerializer, element))
1190 require(encoder is JsonEncoder) // This class can be encoded only by Json
1193 is Response.Ok -> encoder.json.encodeToJsonElement(dataSerializer, value.data)
1214 val string = Json.encodeToString(responses)
1216 println(Json.decodeFromString<List<Response<Project>>>(string))
1220 > You can get the full code [here](../guide/example/example-json-27.kt).
1222 This gives you fine-grained control on the representation of the `Response` class in the JSON outpu…
1231 ### Maintaining custom JSON attributes
1233 A good example of custom JSON-specific serializer would be a deserializer
1234 that packs all unknown JSON properties into a dedicated field of `JsonObject` type.
1248 to be a separate JSON object and that's not what we want.
1250 To mitigate that, write an own serializer that uses the fact that it works only with the `Json` for…
1260 // Cast to JSON-specific interface
1261 val jsonInput = decoder as? JsonDecoder ?: error("Can be deserialized only by JSON")
1262 // Read the whole content as JSON
1263 val json = jsonInput.decodeJsonElement().jsonObject
1265 val name = json.getValue("name").jsonPrimitive.content
1266 val details = json.toMutableMap()
1277 Now it can be used to read flattened JSON details as `UnknownProject`:
1281 …println(Json.decodeFromString(UnknownProjectSerializer, """{"type":"unknown","name":"example","mai…
1285 > You can get the full code [here](../guide/example/example-json-28.kt).
1321 <!--- MODULE /kotlinx-serialization-json -->
1322 <!--- INDEX kotlinx-serialization-json/kotlinx.serialization.json -->
1324 [Json]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.seriali…
1325 [Json()]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.seria…
1326 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-bu…
1327 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-bu…
1328 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-bu…
1329 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-bu…
1330 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-na…
1331 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-bu…
1332 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-bu…
1333 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-bu…
1334 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-bu…
1335 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-bu…
1336 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-bu…
1337 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-bu…
1338 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-cl…
1339 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-bu…
1340 …tlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-clas…
1341 …tlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-clas…
1342 …tlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-clas…
1343 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-bu…
1344 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-bu…
1345 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-na…
1346 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-el…
1347 [Json.parseToJsonElement]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-j…
1348 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-pr…
1349 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-pr…
1350 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-pr…
1351 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-ar…
1352 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-ob…
1353 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/json-pri…
1354 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/json-arr…
1355 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/json-obj…
1356 …tlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/int.h…
1357 …tlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/int-o…
1358 …tlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/long.…
1359 …tlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/long-…
1360 …ng.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/build-json-…
1361 …ng.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/build-json-…
1362 [Json.decodeFromJsonElement]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serializatio…
1363 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-un…
1364 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-nu…
1365 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-tr…
1366 [Json.encodeToString]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/…
1367 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-co…
1368 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-en…
1369 …nlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-de…
1370 …api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-decoder/deco…
1371 …api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-encoder/enco…
1372 …JsonDecoder.json]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kot…
1373 …JsonEncoder.json]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kot…
1374 [Json.encodeToJsonElement]: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-