Posted In: GSON, JSON

GSON – How to parse input JSON with keys as JAVA reserved keyword

Use com.google.gson.annotations.SerializedName annotation to map json key with POJO field

package com.javausecase.gson;

import org.junit.Test;

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

public class JsonKeyWord {
	@Test
	public void main() throws Exception {
		System.out.println("Start");
		String json = "{\"id\":1, \"public\":\"ac\", \"private\":\"ab\"}";
		Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
				.setPrettyPrinting().create();
		System.out.println(gson.toJson(json));
	}
}

class Info {
	public int id;
	@SerializedName("public")
	public String pubName;
	@SerializedName("private")
	public String PrvName;
}

Tags:

by , on February 23rd, 2018