— GSON, Kotlin, Android — 1 min read
GSON is a popular Java library that provides functionalities for serializing and deserializing Java objects to (and from) JSON. When working with GSON, you may come across the need to control which fields of your Java objects are serialized and deserialized. This is where the @Expose
annotation comes into play. In this article, we will explore the purpose and usage of the @Expose
annotation in GSON, along with some examples to illustrate its functionality.
The @Expose
annotation is a part of the GSON library that allows developers to explicitly mark class members for serialization or deserialization. By default, GSON includes all fields in the serialization and deserialization process unless instructed otherwise. The @Expose
annotation provides a way to selectively include or exclude fields from this process.
To utilize the @Expose
annotation, it's important to add the com.google.gson.annotations.Expose
import at the top of your Kotlin file. Once imported, you can annotate class fields that you want to include or exclude during serialization or deserialization.
Let's take a look at an example using a simple data class:
1import com.google.gson.annotations.Expose2import com.google.gson.Gson3
4data class User(5 @Expose val id: Int,6 @Expose val name: String,7 val email: String8)9
10fun main() {11 val user = User(1, "John Doe", "john@example.com")12 val gson = Gson()13 val json = gson.toJson(user)14 println(json)15}
In this example, the id
and name
fields are annotated with @Expose
. When the toJson
function is called, only these annotated fields will be included in the resulting JSON string.
You can also use the @Expose
annotation to exclude specific fields from serialization and deserialization. This can be achieved by setting the serialize
and deserialize
attributes of the @Expose
annotation to false
.
1data class User(2 @Expose val id: Int,3 @Expose val name: String,4 @Expose(serialize = false, deserialize = false) val email: String5)6
7fun main() {8 val user = User(1, "John Doe", "john@example.com")9 val gson = Gson()10 val json = gson.toJson(user)11 println(json)12}
In this modified example, the email
field is now excluded from both serialization and deserialization by setting the serialize
and deserialize
attributes to false
.
By utilizing the @Expose
annotation effectively, developers can ensure that their JSON payloads contain precisely the data they intend, offering flexibility and security throughout the serialization and deserialization process.