LoginSignup
16
14

More than 5 years have passed since last update.

Keyが一意なJSONをJacksonでパースする。

Posted at

「普通、それ値だろ」という情報がキーになってるJSONをJacksonでパースしたい場合。

{ 
  "cat001": { "name": "momo" },
  "cat002": { "name": "chaa" },
  "cat003": { "name": "maru" } 
}

ほぼ下記に書いてあるとおり。
java - how whould I parse JSON with numerical object keys in Jackson JSON - Stack Overflow

public class Main {
    private static String json = "{ \"cat001\": { \"name\": \"momo\" }, \"cat002\": { \"name\": \"chaa\" }, \"cat003\": { \"name\": \"maru\" } }";

    public static void main(String[] args) throws JsonProcessingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(json);
        Iterator<String> fieldNames = root.getFieldNames();
        while (fieldNames.hasNext()) {
            String fieldName = fieldNames.next();
            JsonNode node = root.get(fieldName);
            System.out.println(node.toString());
        }
    }
}

結果:

{"name":"momo"}
{"name":"chaa"}
{"name":"maru"}
16
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
14