How do you exclude fields from serialization in GSON?
A) By using the @Expose annotation
B) By using the @SerializedName annotation
C) By overriding the toString() method
D) By setting a flag in the JSON
Answer:
A) By using the @Expose annotation
Explanation:
In GSON, you can exclude fields from serialization by using the @Expose
annotation in combination with a custom Gson
instance that is configured to respect the annotation. The @Expose
annotation can be applied to fields that should be included or excluded from the JSON output.
For example:
public class SomeClass {
@Expose
private String name;
private int age;
}
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(someObject);
In this example, only the name
field, which is annotated with @Expose
, will be included in the JSON output, while the age
field will be excluded.