you can do that using @Expose annotation.
import com.google.gson.annotations.Expose;
public class Book {
@Expose
private String author;
@Expose
private String title;
private Integer year;
private Double price;
public Book() {
this("test.org", "Exclude properties with Gson", 1989, 49.55);
}
public Book(String author, String title, Integer year, Double price) {
this.author = author;
this.title = title;
this.year = year;
this.price = price;
}
}
.
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class WriteGson {
public static void main(String[] args) {
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create();
String json = gson.toJson(new Book());
System.out.println(json);
Gson gsonNonExcluded = new Gson();
String jsonNonExcluded = gsonNonExcluded.toJson(new Book());
System.out.println(jsonNonExcluded);
}
}
{"author":"test.org","title":"Exclude properties with Gson"}
{"author":"test.org","title":"Exclude properties with Gson","year":1989,"price":49.55}