Jackson でJSON読込み key-value の Stream生成

先日の
oboe2uran.hatenablog.com

さらに、以下のメソッドも追加すると便利かもしれない。

public Stream<Entry<String, Object>> stream(String jsontxt){
   Stream.Builder<Entry<String, Object>> builder = Stream.builder();
   ObjectMapper mapper = new ObjectMapper();
   try{
      parseJson(mapper.readTree(jsontxt), "", builder);
   }catch (JsonProcessingException e){
      throw new RuntimeException(e);
   }
   return  builder.build();
}

public Stream<Entry<String, Object>> stream(InputStream in){
   Stream.Builder<Entry<String, Object>> builder = Stream.builder();
   ObjectMapper mapper = new ObjectMapper();
   try{
      parseJson(mapper.readTree(in), "", builder);
   }catch (JsonProcessingException e){
      throw new RuntimeException(e);
   }catch(IOException e){
      throw new RuntimeException(e);
   }
   return  builder.build();
}

private void parseJson(JsonNode node, String path, Stream.Builder<Entry<String, Object>> builder){
   if (node.getNodeType().equals(JsonNodeType.OBJECT)) {
      for(Iterator<Entry<String, JsonNode>> it=node.fields(); it.hasNext();) {
         Entry<String, JsonNode> entry = it.next();
         parseJson(entry.getValue(), path + "." + entry.getKey(), builder);
      }
   }else if(node.getNodeType().equals(JsonNodeType.ARRAY)){
      if (node.size() > 0){
         int x=0;
         for(Iterator<JsonNode> it=node.iterator(); it.hasNext();x++){
            parseJson(it.next(), path + "[" + x + "]", builder);
         }
      }else{
         builder.add(new SimpleEntry<String, Object>(path.substring(1), new ArrayList<Object>()));
      }
   }else if(node.getNodeType().equals(JsonNodeType.NULL)){
      builder.add(new SimpleEntry<String, Object>(path.substring(1), null));
   }else if(node.getNodeType().equals(JsonNodeType.NUMBER)){
      if (node.isDouble()){
         builder.add(new SimpleEntry<String, Object>(path.substring(1), node.asDouble()));
      }else if(node.isLong()){
         builder.add(new SimpleEntry<String, Object>(path.substring(1), node.asLong()));
      }else{
         builder.add(new SimpleEntry<String, Object>(path.substring(1), node.asInt()));
      }
   }else if(node.getNodeType().equals(JsonNodeType.BOOLEAN)){
      builder.add(new SimpleEntry<String, Object>(path.substring(1), node.asBoolean()));
   }else if(node.getNodeType().equals(JsonNodeType.STRING)){
      builder.add(new SimpleEntry<String, Object>(path.substring(1), node.asText()));
   }
}