Automatically filled the declared non-null field is missing or null with default value.

Overview

[TOC]

Moshi-kotlin-nullsafe 中文版

1. moshi-kotlin

moshi-kotlin support kotlin type safe check.

When parsing json, fields declared as non-null types may throw JsonDataException

  1. Missing property:JsonDataException("Non-null value '%s' was null at %s")
  2. Unexpected null value:JsonDataException("Required value '%s' missing at %s")

For example:

data class User(
  val name: String,
  val age: Int, 
  val address: String
)

val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .build()
val json = """
    {
     "name": "Tom",
     "age": 10
   }
""".trimIndent()
// com.squareup.moshi.JsonDataException: Required value 'address' missing at $
moshi.adapter(User::class.java).fromJson(json)

2. moshi-kotlin-nullsafe

moshi-kotlin-nullsafe aims to solve the above problem.

When the declared non-null field is missing or null, the default value will be automatically filled.

Type Default value
Int 0
Char 0.toChar()
Byte 0.toByte()
Float 0.toFloat()
Double 0.toDouble()
Long 0.toLong()
String ""
Boolean false
List Collections.EMPTY_LIST
Map Collections.EMPTY_MAP
Set Collections.EMPTY_SET

2.1 How to?

Step 1. Add the JitPack repository to your build file

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

Step 2. Add the dependency

dependencies {
    implementation 'com.github.sparklexin:moshi-kotlin-nullsafe:${latest_version}'
}

2.2 Usage

data class User(
  val name: String,
  val age: Int, 
  val address: String
)

val moshi = Moshi.Builder()
    .add(NullSafeStandardJsonAdapters.FACTORY)
    .add(NullSafeKotlinJsonAdapterFactory())
    .build()
val json = """
    {
     "name": "Tom",
     "age": 10
   }
""".trimIndent()
val user = moshi.adapter(User::class.java).fromJson(json)

// User(name=Tom, age=10, address=)
println(user)

retrofit2 converter-moshi

val nullSafeMoshi = Moshi.Builder()
    .add(NullSafeStandardJsonAdapters.FACTORY)
    .add(NullSafeKotlinJsonAdapterFactory())
    .build()

val retrofit = Retrofit.Builder()
    .baseUrl(API_URL)
    .addConverterFactory(MoshiConverterFactory.create(nullSafeMoshi))
    .build()

2.3 Customize

NullSafeKotlinJsonAdapterFactory uses BuildInDefaultValueProvider by default to provide default values:

internal class BuildInDefaultValueProvider : DefaultValueProvider {
    override fun provideDefaultValue(kType: KType): Any? {
        return when (kType.classifier) {
            Int::class -> 0
            Char::class -> 0.toChar()
            Byte::class -> 0.toByte()
            Float::class -> 0.toFloat()
            Double::class -> 0.toDouble()
            Long::class -> 0.toLong()
            String::class -> ""
            Boolean::class -> false
            List::class -> Collections.EMPTY_LIST
            Map::class -> Collections.EMPTY_MAP
            Set::class -> Collections.EMPTY_SET
            else -> null
        }
    }
}

Developers can use your own DefaultValueProvider to support more types.

class NullSafeKotlinJsonAdapterFactory(
    private val providers: List<DefaultValueProvider> = listOf(),
    private val useBuildInProviders: Boolean = true
)
You might also like...
A Kotlin compiler plugin that allows Java callers to pass in null for default parameters

kotlin-null-defaults (Compiler plugin) (Gradle Plugin) ( Currently pending approval) A Kotlin compiler plugin that allows Java callers to pass in null

Open as default - A flutter plugin that allows setting up your flutter app to open files as default
Open as default - A flutter plugin that allows setting up your flutter app to open files as default

open_as_default A flutter plugin that allows setting up your flutter app to open

🛠️ The missing drawable toolbox for Android. Create drawables programmatically and get rid of the boring and always repeated drawable.xml files.
🛠️ The missing drawable toolbox for Android. Create drawables programmatically and get rid of the boring and always repeated drawable.xml files.

DrawableToolbox English | 中文 The missing DrawableToolbox for Android. Create drawables programmatically and get rid of the boring and always repeated

🍞 The missing toast library for Android.
🍞 The missing toast library for Android.

Literally Toast 🍞 A toast library for Android. Usage: 🔥 Use the LitToast to get lit and show your users a proper toast. LitToast.create(context, "My

Lyricist - The missing I18N and I10N library for Jetpack Compose!

Jetpack Compose greatly improved the way we build UIs on Android, but not how we interact with strings. stringResource() works well, but doesn't benefit from the idiomatic Kotlin like Compose.

Missing safe arguments generator for Compose Navigation

Safe Arguments Generator Yet another attempt to add safe arguments to Compose Navigation. Why Since routes in Navigation Component don't support safe

This library is used to control an attribute if it comes to null

This library is used to control an attribute if it comes to null, what it will do is remove that null and give it a default value. Ideal for dealing with business models where attributes can be nullable.

Default colors and dimens per Material Design guidelines and Android Design guidelines inside one library.
Default colors and dimens per Material Design guidelines and Android Design guidelines inside one library.

Material Design Dimens Default colors and dimens per Material Design guidelines and Android Design guidelines inside one library. Dimens Pattern: R.di

 A dual-function menu button that offers a default action as well as the possibility of choosing a different action by selecting from a set of alternatives.
A dual-function menu button that offers a default action as well as the possibility of choosing a different action by selecting from a set of alternatives.

A dual-function menu button that offers a default action as well as the possibility of choosing a different action by selecting from a set of alternatives.

SmartClient is a library that contains the default implementations to idenify a client.

SmartClient is a library that contains the default implementations to idenify a client.

♣️ A flexible and powerful command framework with default Guilded API implementations using deck

A simple and versatile command framework made with the primary objective of making Guilded command experience a little more elegant.

Colorful Sliders written with Jetpack Compose that enliven default sliders
Colorful Sliders written with Jetpack Compose that enliven default sliders

🚀🌈 😍 Colorful Sliders written with Jetpack Compose that enliven default sliders with track and thumb dimensions, and gradient colors, borders, labels on top or at the bottom move with thumb and ColorfulIconSlider that can display emoji or any Composable as thumb

Project of an sdk user, for default implementations of login/register user
Project of an sdk user, for default implementations of login/register user

Login_Manager Project of an sdk user, for default implementations of login/register user Implementation For use, is necessary: configure the feature c

Material Design text field that comes in a box, based on (OLD) Google Material Design guidelines.
Material Design text field that comes in a box, based on (OLD) Google Material Design guidelines.

TextFieldBoxes A new Material Design text field that comes in a box, based on Google Material Design guidelines. 🇨🇳 中文看这里 UPDATE NOTICE 1.4.5 Releas

An app that is a one-stop destination for all the CS enthusiasts, providing resources like Information scrapping techniques, best YT channels, courses available free-of-cost, etc.  & knowledge about every domain and field that exists on the Internet related to Computer Science along with News, Jobs, and Internships opportunities in these domains along with valuable tips and hacks from mentors for a particular domain.
An app that is a one-stop destination for all the CS enthusiasts, providing resources like Information scrapping techniques, best YT channels, courses available free-of-cost, etc. & knowledge about every domain and field that exists on the Internet related to Computer Science along with News, Jobs, and Internships opportunities in these domains along with valuable tips and hacks from mentors for a particular domain.

An app that is a one-stop destination for all the CS enthusiasts, providing resources like Information scrapping techniques, best YT channels, courses available free-of-cost, etc. & knowledge about every domain and field that exists on the Internet related to Computer Science along with News, Jobs, and Internships opportunities in these domains along with valuable tips and hacks from mentors for a particular domain.

An address-autocompleting text field for Android
An address-autocompleting text field for Android

android-PlacesAutocompleteTextView An AutocompleteTextView that interacts with the Google Maps Places API to provide location results and caches selec

A module designed to encapsulate the use of an Android EditText field for gathering currency information from a user. Supports all ISO-3166 compliant locales/currencies.
A module designed to encapsulate the use of an Android EditText field for gathering currency information from a user. Supports all ISO-3166 compliant locales/currencies.

CurrencyEditText CurrencyEditText is an extension of Android's EditText view object. It is a module designed to provide ease-of-use when using an Edit

Field state manager and basic set of validation, fields
Field state manager and basic set of validation, fields

Compose Forms Field state manager and basic set of validation, fields

Date text field with on the fly validation built with Jetpack Compose.
Date text field with on the fly validation built with Jetpack Compose.

Date text field with on the fly validation built with Jetpack Compose.

Releases(v1.0.0)
Owner
Android developer
null
Utility library dedicated for functional & non-functional codebases to simplify modelling of success and failure responses for the JVM languages 🔀

Expressible Utility library, part of the panda-lang SDK, dedicated for functional codebases that require enhanced response handling. Express yourself

Panda 28 Nov 14, 2022
Bukkit library written in Kotlin to make with compatibility and ease non-playable-character (NPC)

mc-npk Easy to use, fast and efficient library to make non-playable-characters (

Luiz Otávio 3 Aug 4, 2022
A simple, lightweight, non-bloated redis client for kotlin and other JVM languages

rekt is a lightweight, non-bloated redis client, primarily written for the kotlin programming language, while also supporting other JVM-based languages, such as Java, Scala, and obviously way more.

Patrick 8 Nov 2, 2022
Fully customizable, built from scratch NumberPicker for android. Created as an alternative to non-customizable native android NumberPicker

GoodNumberPicker GoodPicker is an Android library that provides a picker with customizable UI. It was developed as alternative to the default NumberPi

null 3 Nov 30, 2022
An interactive command line interface to a transactional key value store

Transactional Key-Value Store An interactive command line interface to a transactional key value store. Commands: SET <key> <value> // store the value

Eugene 0 Jan 14, 2022
Automatically generates UI demos which allow users to call any function with any parameters

Automatically generates UI demos which allow users to call any function (including composable ones) with any parameters. Useful for building demo screens in playground apps of various design systems.

Anton Popov 3 Jul 28, 2022
Attend HoYoLAB Check-in events automatically

Croissant Attend HoYoLAB Check-in events automatically https://play.google.com/store/apps/details?id=com.joeloewi.croissant Stacks Room Database Hilt

joeloewi 2 Nov 23, 2022
An annotation processor library that automatically creates Hilt's `@Binds` functions and modules.

HiltBinder An annotation processor library that automatically creates Hilt's @Binds functions and modules. If you think this library is useful, please

SangMin Park 5 Sep 19, 2022
A ksp library to automatically generate navigation functions for jetpack compose.

Compose/Navigation/Generator ⚠️ This library is still under development and not considered stable! Content Introduction Usage Example: Single destinat

Steffen Eckardt 4 Sep 13, 2022
Checks for app updates and automatically updates the current app if the new one in local storage have a different version

Silent Android App Update Sample This sample shows how to update Android app silently without user confirmation with a device owner app. It works on A

Hamdi Guerbej 1 May 14, 2022