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

JavaJSONObject Oriented ProgrammingProgramming

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" com.google.gson.JsonSyntaxException: duplicate key"

Syntax

public class TypeToken<T> extends Object

Example

import java.lang.reflect.Type;
import java.util.Map;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
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);
      System.out.println(map);
   }
}

Output

{123=abc, 124=def, 125=ghi}
raja
Published on 04-Oct-2019 09:20:44
Advertisements