cbeust / klaxon

A JSON parser for Kotlin
Apache License 2.0
1.85k stars 122 forks source link

#344 Add instance-wide settings #359

Closed waltkb closed 2 years ago

waltkb commented 2 years ago

This pull request adds the ability to optionally supply settings for a Klaxon instance in the constructor. These instance wide settings complement the settings of individual attributes set with @Json(...).

val settings = KlaxonSettings(serializeNull = false)

Currently, it is only implemented for serializeNull, however, it is simple to extend for future uses too.

This allows to e.g. write:

data class User(
    val username: String, val email: String, // mandatory
    val phone: String?, val fax: String?, val age: Int? // optional
)

Klaxon(settings)
  .toJsonString(User("user", "user@example.org", null, null, null))

// displays {}

instead of having to add these options to every attribute like this:

data class User(
    val username: String, val email: String, // mandatory
    @Json(serializeNull = false) val phone: String?,  // optional
    @Json(serializeNull = false) val fax: String?,  // optional
    @Json(serializeNull = false) val age: Int? // optional
)

The documentation was extended to illustrate this feature, and a test class was added to check its functionality.

Fixes #344