Java examples for JSON:JSON Data
pretty Format JSON
import java.net.URL; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.transaction.UserTransaction; public class Main{ public static String prettyFormatJSON(String jsonString) { int level = 0; boolean newline = false; StringBuilder builder = new StringBuilder(); char p = '\0'; for (char c : jsonString.toCharArray()) { if (newline && (c != '}' && c != ']' && c != ',' && (c != '{' || p != '['))) { builder.append('\n'); for (int i = 0; i < level; i++) builder.append(" "); newline = false;/*from ww w.ja v a 2 s . c o m*/ } switch (c) { case '{': case '[': builder.append(c); level++; newline = true; break; case ',': builder.append(c); newline = true; break; case '}': case ']': level--; if (c != ']' || p != '}') { builder.append('\n'); for (int i = 0; i < level; i++) builder.append(" "); } builder.append(c); newline = true; break; default: builder.append(c); break; } p = c; } return builder.toString(); } }