How to parse a JSON without duplicate keys using Gson in Java?

A Gson is a JSON library for Java, which is created by Google. By using Gson, we can generate JSON and convert JSON to Java objects. We can create a Gson instance by creating a GsonBuilder instance and calling with the create() method. We can parse a JSON without duplicate keys using the TypeToken class. If we want to create a type literal for Map, we can create an empty anonymous inner class. If we try to insert a duplicate key, it will generate an error at runtime, "Exception in thread "main" duplicate key"


public class TypeToken<T> extends Object


import java.lang.reflect.Type;
import java.util.Map;
public class JsonWithoutDuplicateKeysTest {
   public static void main(String args[]) throws Exception {
      String json = "{\"123\":\"abc\", \"124\":\"def\", \"125\":\"ghi\"}";
      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      Type mapType = new TypeToken<Map<Integer, String>>() {}.getType();
      Map<String, String> map = gson.fromJson(json, mapType);


{123=abc, 124=def, 125=ghi}