Skip to content

Instantly share code, notes, and snippets.

@abdus
Last active April 23, 2023 23:18
Show Gist options
  • Save abdus/4eceecb71ef6001410c48a2423ff5ee0 to your computer and use it in GitHub Desktop.
Save abdus/4eceecb71ef6001410c48a2423ff5ee0 to your computer and use it in GitHub Desktop.
How to serialize a JSON with `null` values in Kotlin using the Gson Library
/**
* the first example uses Kotlin's data classes to define the structure
* this is the suitable approach if the classes are already defined
*/
data class UserData(
var user_id: String? = null,
var user_name: String? = null
) {}
class MainActivity : AppCompatActivity() {
val gson = GsonBuilder().serializeNulls().create();
// serializeNulls() method will ensure that the properties with null values
// are included in the serialized JSON String
val jsonStr = gson.toJson(UserData("user_123456", null)).toString();
Log.i("json", jsonStr);
// {"user_id":"user_123456","user_name":null}
}
/**
* the second example uses Gson's JsonObject class. this should be your go-to
* approach is you are building the object on-the-fly
*/
class MainActivity : AppCompatActivity() {
val gson = GsonBuilder().serializeNulls().create();
// serializeNulls() method will ensure that the properties with null values
// are included in the serialized JSON String
val jsonObject = JsonObject();
jsonObject.add("user_name", JsonNull.INSTANCE);
jsonObject.addProperty("user_id", "user_123456");
val jsonStr = gson.toJson(jsonObject).toString();
Log.i("json", jsonStr);
// {"user_name":null,"user_id":"user_123456"}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment