Posted In: GSON, JSON

GSON – How to parse input JSON with dynamic keys

Use Map to parse this JSON. This will work as JSON cannot have duplicate keys.

package com.javausecase.gson;

import java.lang.reflect.Type;
import java.util.Map;

import org.junit.Test;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class DynamicJsonKeys {
	@Test
	public void main() throws Exception {
		System.out.println("Start");
		String json = "{\"123\":\"ac\", \"124\":\"ab\", \"125\":\"aa\"}";
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		Type mapType = new TypeToken<Map<Integer, String>>() {
		}.getType();
		Map<String, String> result = gson.fromJson(json, mapType);
		System.out.println(result);
	}
}

Tags:

by , on February 23rd, 2018