Posted In: GSON, JSON

GSON – How to exclude fields during serialization/toJSON

Use com.google.gson.annotations.Expose to exclude

package com.javausecase.gson.serialize;

import org.junit.Test;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;

public class ExcludeField {
	@Test
	public void main() throws Exception {
		System.out.println("Start");
		Student st = new Student();
		st.id = 123;
		st.firstName = "abc";
		st.maiingAddress = "California 90089";
		Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
				.setPrettyPrinting().create();

		System.out.println(gson.toJson(st));
	}

}

class Student {
	@Expose
	public int id;
	@Expose
	public String firstName;
	public String maiingAddress;
}

Output maiingAddress is excluded

{
  "id": 123,
  "firstName": "abc"
}

by , on February 22nd, 2018

  • Categories