From 85e86f1fa87f7862004c4d02ef976f55ce93d8c5 Mon Sep 17 00:00:00 2001 From: Erik Huizinga Date: Tue, 4 Dec 2018 04:50:52 +0100 Subject: [PATCH] Add section about null safety (#757) * Add section about null safety Null safety is an important feature of the Kotlin language. The fact that Moshi supports wrapping existing adapters in a null safe or non-null variant is important for null safety. Therefore it makes sense to promote this feature in the readme, as this is one of the first places people should look for support and such features. * Move factory method section out of Kotlin section * Fix syntax highlighting * Remove isLenient() reference * Rewrite Kotlin example as Java, reformat comments --- README.md | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7ad05b2..91618bc 100644 --- a/README.md +++ b/README.md @@ -213,11 +213,44 @@ JsonAdapter jsonAdapter = moshi.adapter(Event.class); Event event = jsonAdapter.fromJson(json); ``` +### Adapter convenience methods + +Moshi provides a number of convenience methods for `JsonAdapter` objects: +- `nullSafe()` +- `nonNull()` +- `lenient()` +- `failOnUnknown()` +- `indent()` +- `serializeNulls()` + +These factory methods wrap an existing `JsonAdapter` into additional functionality. +For example, if you have an adapter that doesn't support nullable values, you can use `nullSafe()` to make it null safe: + +```java +String dateJson = "\"2018-11-26T11:04:19.342668Z\""; +String nullDateJson = "null"; + +// RFC 3339 date adapter, doesn't support null by default +// See also: https://github.com/square/moshi/tree/master/adapters +JsonAdapter adapter = new Rfc3339DateJsonAdapter(); + +Date date = adapter.fromJson(dateJson); +System.out.println(date); // Mon Nov 26 12:04:19 CET 2018 + +Date nullDate = adapter.fromJson(nullDateJson); +// Exception, com.squareup.moshi.JsonDataException: Expected a string but was NULL at path $ + +Date nullDate = adapter.nullSafe().fromJson(nullDateJson); +System.out.println(nullDate); // null +``` + +In contrast to `nullSafe()` there is `nonNull()` to make an adapter refuse null values. Refer to the Moshi JavaDoc for details on the various methods. + ### Parse JSON Arrays Say we have a JSON string of this structure: -```java +```json [ { "rank": "4",