Posted In: GSON, JSON
GSON – How to exclude fields during serialization/toJSON using JsonSerializer
Use com.google.gson.JsonSerializer to add only required fields
package com.javausecase.gson.serialize; import java.lang.reflect.Type; import org.junit.Test; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class ExcludeField2 { @Test public void main() throws Exception { System.out.println("Start"); Student2 st = new Student2(); st.id = 123; st.firstName = "abc"; st.maiingAddress = "California 90089"; Gson gson = new GsonBuilder() .registerTypeAdapter(Student2.class, new Student2Serialiser()) .setPrettyPrinting().create(); System.out.println(gson.toJson(st)); } } class Student2 { public int id; public String firstName; public String maiingAddress; } class Student2Serialiser implements JsonSerializer<Student2> { @Override public JsonElement serialize(final Student2 st, final Type typeOfSrc, final JsonSerializationContext context) { final JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("id", st.id); jsonObject.addProperty("firstName", st.firstName); return jsonObject; } }
Output maiingAddress is excluded
{ "id": 123, "firstName": "abc" }
Tags: How do I write a custom JSON deserializer for Gson
- Apache (13)
- Build Tools (2)
- Gradle (2)
- Caching (1)
- cpanel (1)
- cURL (1)
- Database (7)
- Hibernate (5)
- Java Core (38)
- Java Script (15)
- Bootstrap (1)
- File Upload (7)
- jQuery (3)
- React (3)
- JEE (13)
- JSON (41)
- GSON (13)
- Jackson 1X (1)
- Jackson 2X (12)
- jsoniter (1)
- Logging (2)
- Apache Commons Logging (1)
- Apache Log4J (1)
- Logback (1)
- SLF4J (1)
- MongoDB (1)
- OS (1)
- Linux (1)
- Security (5)
- Server (4)
- Tomcat (4)
- Service (2)
- Micro (2)
- Spring (46)
- Pattern (2)
- Spring Boot (20)
- Spring Data (4)
- Spring MVC (8)
- Spring REST (13)
- Spring Security (7)
- Testing (11)
- XML (5)
- JDOM XML Parser (1)