comparison src/goodjava/json/JsonToString.java @ 1518:f989778ca9e1

stringify, json_string
author Franklin Schmidt <fschmidt@gmail.com>
date Fri, 19 Jun 2020 17:50:25 -0600
parents 6a24c8b33d6b
children 99a8ac891914
comparison
equal deleted inserted replaced
1517:04615093b19d 1518:f989778ca9e1
6 6
7 7
8 public final class JsonToString { 8 public final class JsonToString {
9 public boolean compressed = false; 9 public boolean compressed = false;
10 10
11 private String colon;
12 private String comma;
13
14 public static final class JsonException extends RuntimeException { 11 public static final class JsonException extends RuntimeException {
15 private JsonException(String msg) { 12 private JsonException(String msg) {
16 super(msg); 13 super(msg);
17 } 14 }
18 } 15 }
19 16
20 public String toString(Object obj) throws JsonException { 17 public String toString(Object obj) throws JsonException {
21 colon = compressed ? ":" : ": ";
22 comma = compressed ? "," : ", ";
23 StringBuilder sb = new StringBuilder(); 18 StringBuilder sb = new StringBuilder();
24 toString(obj,sb,0); 19 toString(obj,sb,0);
25 if( !compressed ) 20 if( !compressed )
26 sb.append('\n'); 21 sb.append('\n');
27 return sb.toString(); 22 return sb.toString();
121 if( !list.isEmpty() ) { 116 if( !list.isEmpty() ) {
122 indent(sb,indented+1); 117 indent(sb,indented+1);
123 toString(list.get(0),sb,indented+1); 118 toString(list.get(0),sb,indented+1);
124 final int n = list.size(); 119 final int n = list.size();
125 for( int i=1; i<n; i++ ) { 120 for( int i=1; i<n; i++ ) {
126 sb.append(comma); 121 sb.append(',');
122 indent(sb,indented+1);
127 toString(list.get(i),sb,indented+1); 123 toString(list.get(i),sb,indented+1);
128 } 124 }
129 indent(sb,indented); 125 indent(sb,indented);
130 } 126 }
131 sb.append(']'); 127 sb.append(']');
151 private void toString(Map.Entry entry,StringBuilder sb,int indented) throws JsonException { 147 private void toString(Map.Entry entry,StringBuilder sb,int indented) throws JsonException {
152 Object key = entry.getKey(); 148 Object key = entry.getKey();
153 if( !(key instanceof String) ) 149 if( !(key instanceof String) )
154 throw new JsonException("table keys must be strings but got "+key.getClass().getSimpleName()+" ("+key+"="+entry.getValue()+")"); 150 throw new JsonException("table keys must be strings but got "+key.getClass().getSimpleName()+" ("+key+"="+entry.getValue()+")");
155 toString((String)key,sb); 151 toString((String)key,sb);
156 sb.append(colon); 152 sb.append( compressed ? ":" : ": " );
157 toString(entry.getValue(),sb,indented); 153 toString(entry.getValue(),sb,indented);
158 } 154 }
159 155
160 private void indent(StringBuilder sb,int indented) { 156 private void indent(StringBuilder sb,int indented) {
161 if( compressed ) 157 if( compressed )