Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

40
LINES

< > BotCompany Repo | #1026299 - jsonEncode_breakAtNLevels - jsonEncode with line breaks in first n levels

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (2256L/14K).

sS jsonEncode_breakAtNLevels(int levels, O o) {
  new StringBuilder buf;
  jsonEncode_breakAtNLevels(1, levels, o, buf);
  ret str(buf);
}

svoid jsonEncode_breakAtNLevels(int level, int levels, O o, StringBuilder buf) {
  if (o == null)
    buf.append("null");
  else if (o instanceof S)
    buf.append(quote((S) o));
  else if (o instanceof Number || o instanceof Bool)
    buf.append(o);
  else if (o instanceof Map) {
    Map map = cast o;
    buf.append("{");
    bool first = true;
    for (O key : keys(map)) {
      if (first) first = false; else buf.append(",");
      if (level <= levels) buf.append("\n" + indent(level*2));
      buf.append(quote((S) key));
      buf.append(":");
      jsonEncode_breakAtNLevels(level+1, levels, map.get(key), buf);
    }
    if (level <= levels) buf.append("\n" + indent((level-1)*2));
    buf.append("}");
  } else if (o instanceof Collection) {
    Collection l = cast o;
    buf.append("[");
    bool first = true;
    for (O element : l) {
      if (first) first = false; else buf.append(",");
      if (level <= levels) buf.append("\n" + indent(level*2));
      jsonEncode_breakAtNLevels(level+1, levels, element, buf);
    }
    if (level <= levels) buf.append("\n" + indent((level-1)*2));
    buf.append("]");
  } else
    fail("Unknown object for JSON encoding: " + className(o));
}

Author comment

Began life as a copy of #1012984

download  show line numbers  debug dex   

Travelled to 4 computer(s): bhatertpkbcr, mqqgnosmbjvj, pzhvpgtvlbxg, tvejysmllsmz

No comments. add comment

Snippet ID: #1026299
Snippet name: jsonEncode_breakAtNLevels - jsonEncode with line breaks in first n levels
Eternal ID of this version: #1026299/5
Text MD5: 6e88f7a1a0e88107b27961de49f37f5c
Transpilation MD5: 7932d220c90134f6b23c34c1e26029de
Author: stefan
Category: javax / json
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-12-13 19:48:45
Source code size: 1375 bytes / 40 lines
Pitched / IR pitched: No / No
Views / Downloads: 38 / 71
Version history: 4 change(s)
Referenced in: [show references]

Formerly at http://tinybrain.de/1026299 & http://1026299.tinybrain.de