Home  >  Article  >  Java  >  How to avoid duplicate keys when parsing JSON using Gson in Java?

How to avoid duplicate keys when parsing JSON using Gson in Java?

王林
王林forward
2023-09-07 10:57:021381browse

How to avoid duplicate keys when parsing JSON using Gson in Java?

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"

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}

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete