你可以使用@Expose註釋來做到這一點。
import com.google.gson.annotations.Expose;
公共類圖書{
@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;
}
}
進口com.google.gson.Gson; import com.google.gson.GsonBuilder;
公共類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);
}
}
{ 「作者」:「測試。「」作者「:」test.org「,」標題「:」與Gson排除屬性「,」年份「:1989,」價格「:49.55}
你可以使用getter-setter方法 – Nisarg
你爲什麼不手動創建的,而不是使用庫中的JSON JSONObject的JSON =新的JSONObject(); json.put(鍵,值); 返回JSON; –
告訴我你的json – Rahul