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?
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).
GSON can use the Object definition to directly create an object of the desired type. While JSONObject needs to be parsed manually.
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.
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"
}
}
With Java 8+ and without TypeToken:
new Gson().fromJson(jsonString, JsonObject.class).getAsJsonObject("mappings")
.entrySet().stream().forEach(System.out::println);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With