<init>(block: JsonBuilder.() -> Unit)
DSL-like constructor for Json. This constructor is marked with unstable default: its default parameters values and behaviour may change in the next releases.
(common, js, jvm, native)<init>(configuration: JsonConfiguration = JsonConfiguration.Stable, context: SerialModule = EmptyModule)
The main entry point to work with JSON serialization. It is typically used by constructing an application-specific instance, with configured json-specific behaviour (configuration constructor parameter) and, if necessary, registered custom serializers (in SerialModule provided by context constructor parameter). Then constructed instance can be used either as regular SerialFormat or StringFormat or for converting objects to JsonElement back and forth.
This is the only serial format which has first-class JsonElement support. Any serializable class can be serialized to or from JsonElement with Json.fromJson and Json.toJson respectively or serialize properties of JsonElement type.
Example of usage:
@Serializable
class DataHolder(val id: Int, val data: String, val extensions: JsonElement)
val json = Json(JsonConfiguration.Default)
val instance = DataHolder(42, "some data", json { "additional key" to "value" })
// Plain StringFormat usage
val stringOutput: String = json.stringify(instance)
// JsonElement serialization specific for Json only
val jsonTree: JsonElement = json.toJson(instance)
// Deserialize from string
val deserialized: DataHolder = json.parse<DataHolder>(stringOutput)
// Deserialize from json tree, Json-specific
val deserializedFromTree: DataHolder = json.fromJson<DataHolder>(jsonTree)
// Deserialize from string to json tree, Json-specific
val deserializedToTree: JsonElement = json.fromJson<JsonElement>(stringOutput)
Note that @ImplicitReflectionSerializer
are used in order to omit DataHolder.serializer
, but this is a temporary limitation.