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:

by , on February 22nd, 2018

  • Categories