Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON with GSON without a model

Tags:

java

json

gson

Suppose you have a JSON object:

{
  "mappings": {
    "s54dsf45fzd324": "135sdq13sod1tt3",
    "21sm24dsfp2ds2": "123sd56f4gt4ju4"
  }
}

The only thing you know about the mappings object is that it maps strings to strings, but you do not know the key values.

Is it possible to parse this object with GSON and cycle through the key/value pairs?

like image 673
Maarten Avatar asked May 25 '14 18:05

Maarten


People also ask

Does GSON offer parse () function?

The GSON JsonParser class can parse a JSON string or stream into a tree structure of Java objects. GSON also has two other parsers. The Gson JSON parser which can parse JSON into Java objects, and the JsonReader which can parse a JSON string or stream into tokens (a pull parser).

Is GSON better than JSON?

GSON can use the Object definition to directly create an object of the desired type. While JSONObject needs to be parsed manually.

What is the difference between GSON and Jackson?

Conclusion Both Gson and Jackson are good options for serializing/deserializing JSON data, simple to use and well documented. Advantages of Gson: Simplicity of toJson/fromJson in the simple cases. For deserialization, do not need access to the Java entities.


2 Answers

Simply try with TypeToken that will return a Map<String, Map<String, String>> as Type.

Reader reader=new BufferedReader(new FileReader(new File("resources/json.txt")));

Type type = new TypeToken<Map<String, Map<String, String>>>() {}.getType();
Map<String, Map<String, String>> data = new Gson().fromJson(reader, type);

// pretty printing 
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));

output:

{
    "mappings": {
      "s54dsf45fzd324": "135sdq13sod1tt3",
      "21sm24dsfp2ds2": "123sd56f4gt4ju4"
    }
}
like image 96
Braj Avatar answered Sep 29 '22 06:09

Braj


With Java 8+ and without TypeToken:

    new Gson().fromJson(jsonString, JsonObject.class).getAsJsonObject("mappings")
    .entrySet().stream().forEach(System.out::println);
like image 45
GabrielBB Avatar answered Sep 29 '22 08:09

GabrielBB