Gson is a Java JSON library 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 the create() method. We can use the TypeToken class to parse JSON without duplicate keys. If we wanted to create a type literal for Map, we could 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"
public class TypeToken<T> extends Object
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); } }
{123=abc, 124=def, 125=ghi}
The above is the detailed content of How to avoid duplicate keys when parsing JSON using Gson in Java?. For more information, please follow other related articles on the PHP Chinese website!