import java.util.Stack; import java.util.stream.Collectors; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class JsonConverter extends NlpBaseListener { public JsonConverter() { mGsonInstance = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); mRoot = new JsonObject(); mSection = new JsonArray(); mSectionStack = new Stack(); } /* ========== JSON related stuff ========== */ Gson mGsonInstance; public String buildJsonString() { return mGsonInstance.toJson(mRoot); } /* ========== Section layout related stuff ========== */ JsonObject mRoot; JsonArray mSection; Stack mSectionStack; private void pushSection() { mSectionStack.push(mSection); mSection = new JsonArray(); } private void popSection() { mSection = mSectionStack.pop(); } /* ========== Listener ========== */ @Override public void enterDocument(NlpParser.DocumentContext ctx) { // insert language prop mRoot.addProperty("language", StringHelper.cutLanguageHead(ctx.LANG_HEADER().getText())); } @Override public void exitDocument(NlpParser.DocumentContext ctx) { // insert document prop mRoot.add("entries", mSection); } @Override public void enterSection(NlpParser.SectionContext ctx) { pushSection(); } @Override public void exitSection(NlpParser.SectionContext ctx) { // create new object JsonObject objSection = new JsonObject(); objSection.addProperty("section", StringHelper.cutSectionHead(ctx.SECTION_HEAD().getText())); objSection.add("entries", mSection); // pop and insert popSection(); mSection.add(objSection); } @Override public void enterSubSection(NlpParser.SubSectionContext ctx) { pushSection(); } @Override public void exitSubSection(NlpParser.SubSectionContext ctx) { // create new object JsonObject objSubSection = new JsonObject(); objSubSection.addProperty("section", StringHelper.cutSectionHead(ctx.SUB_SECTION_HEAD().getText())); objSubSection.add("entries", mSection); // pop and insert popSection(); mSection.add(objSubSection); } @Override public void enterEntryString(NlpParser.EntryStringContext ctx) { mSection.add(StringHelper.processString(ctx.ENTRY_STRING().getText())); } @Override public void enterEntryConcatedString(NlpParser.EntryConcatedStringContext ctx) { mSection.add(StringHelper.processConcatedString( ctx.ENTRY_STRING().stream().map(value -> value.getText()).collect(Collectors.toList()))); } @Override public void enterEntryInteger(NlpParser.EntryIntegerContext ctx) { mSection.add(Integer.parseInt(ctx.ENTRY_INTEGER().getText())); } }