Maarten
Maarten

Reputation: 7308

Parse JSON with GSON without a model

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?

Upvotes: 6

Views: 3712

Answers (2)

GabrielBB
GabrielBB

Reputation: 2679

With Java 8+ and without TypeToken:

    new Gson().fromJson(jsonString, JsonObject.class).getAsJsonObject("mappings")
    .entrySet().stream().forEach(System.out::println);

Upvotes: 1

Braj
Braj

Reputation: 46841

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"
    }
}

Upvotes: 5

Related Questions