JSONSymbolPrinter.java

  1. package com.jeantessier.classreader;

  2. import java.io.*;
  3. import java.util.*;
  4. import java.util.stream.*;

  5. import static java.util.stream.Collectors.*;

  6. public class JSONSymbolPrinter extends SymbolPrinter {
  7.     public JSONSymbolPrinter(PrintWriter out) {
  8.         super(out);
  9.     }

  10.     public void print(SymbolGatherer gatherer) throws IOException {
  11.         var output = "[" +
  12.                 gatherer.stream()
  13.                         .map(this::visitableToRecord)
  14.                         .map(this::recordToJSON)
  15.                                 .collect(joining(",")) +
  16.         "]";
  17.         getOut().println(output);
  18.     }

  19.     private String recordToJSON(Map<String, ?> record) {
  20.         return "{" +
  21.                 record.entrySet().stream()
  22.                         .map(entry -> {
  23.                             if  (entry.getValue() instanceof Stream<?> stream) {
  24.                                 return "\"" + entry.getKey() + "\":[" + format(stream) + "]";
  25.                             } else {
  26.                                 return "\"" + entry.getKey() + "\": \"" + entry.getValue() + "\"";
  27.                             }
  28.                         })
  29.                         .collect(joining(", "))
  30.                 +
  31.                 "}";
  32.     }
  33. }