Home > Java > javaTutorial > body text

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

王林
Release: 2023-09-07 10:57:02
forward
1351 people have browsed it

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
Copy after login

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);
   }
}
Copy after login

Output

{123=abc, 124=def, 125=ghi}
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!