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).

1  
sS jsonEncode_breakAtNLevels(int levels, O o) {
2  
  new StringBuilder buf;
3  
  jsonEncode_breakAtNLevels(1, levels, o, buf);
4  
  ret str(buf);
5  
}
6  
7  
svoid jsonEncode_breakAtNLevels(int level, int levels, O o, StringBuilder buf) {
8  
  if (o == null)
9  
    buf.append("null");
10  
  else if (o instanceof S)
11  
    buf.append(quote((S) o));
12  
  else if (o instanceof Number || o instanceof Bool)
13  
    buf.append(o);
14  
  else if (o instanceof Map) {
15  
    Map map = cast o;
16  
    buf.append("{");
17  
    bool first = true;
18  
    for (O key : keys(map)) {
19  
      if (first) first = false; else buf.append(",");
20  
      if (level <= levels) buf.append("\n" + indent(level*2));
21  
      buf.append(quote((S) key));
22  
      buf.append(":");
23  
      jsonEncode_breakAtNLevels(level+1, levels, map.get(key), buf);
24  
    }
25  
    if (level <= levels) buf.append("\n" + indent((level-1)*2));
26  
    buf.append("}");
27  
  } else if (o instanceof Collection) {
28  
    Collection l = cast o;
29  
    buf.append("[");
30  
    bool first = true;
31  
    for (O element : l) {
32  
      if (first) first = false; else buf.append(",");
33  
      if (level <= levels) buf.append("\n" + indent(level*2));
34  
      jsonEncode_breakAtNLevels(level+1, levels, element, buf);
35  
    }
36  
    if (level <= levels) buf.append("\n" + indent((level-1)*2));
37  
    buf.append("]");
38  
  } else
39  
    fail("Unknown object for JSON encoding: " + className(o));
40  
}

Author comment

Began life as a copy of #1012984

download  show line numbers  debug dex  old transpilations   

Travelled to 6 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt

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: 272 / 376
Version history: 4 change(s)
Referenced in: [show references]