Tôi muốn tuần tự hóa null cho một trường hoặc lớp cụ thể.Gson tuần tự hóa null cho lớp hoặc trường cụ thể
Trong GSON, tùy chọn serializeNulls()
áp dụng cho toàn bộ JSON.
Ví dụ:
class MainClass {
public String id;
public String name;
public Test test;
}
class Test {
public String name;
public String value;
}
MainClass mainClass = new MainClass();
mainClass.id = "101"
// mainClass has no name.
Test test = new Test();
test.name = "testName";
test.value = null;
mainClass.test = test;
Tạo JSON sử dụng GSON:
GsonBuilder builder = new GsonBuilder().serializeNulls();
Gson gson = builder.create();
System.out.println(gson.toJson(mainClass));
ouput hiện tại:
{
"id": "101",
"name": null,
"test": {
"name": "testName",
"value": null
}
}
đầu ra mong muốn:
{
"id": "101",
"test": {
"name": "testName",
"value": null
}
}
Làm thế nào để đạt được kết quả mong muốn?
giải pháp ưu tiên sẽ có các thuộc tính sau:
- Do KHÔNG null serialize theo mặc định,
- null Serialize cho các trường có một chú thích cụ thể.
@DatoMumladze i đã cập nhật câu hỏi của tôi – Martin
Tôi không thể tìm thấy tính năng này trong Gson. Đây là một số [link] thú vị (https://mindfirejavaexperts.wordpress.com/2014/03/14/how-to-use-gson-library/) Hoặc bạn có thể sử dụng Jackson để tuần tự hóa đối tượng thành json và loại trừ các giá trị null cho các trường cụ thể sử dụng chú thích này '@JsonSerialize (include = JsonSerialize.Inclusion.NON_NULL)' –
Có thể trùng lặp của [Loại trừ các trường nhất định khỏi Tuần tự hóa dựa trên giá trị trong GSON] (http://stackoverflow.com/questions/13120354/excluding-certain -trên-serial-based-based-on-value-in-gson) – tima