Recently and a third-party system docking, need to save their request parameters, but that long string of JSON is not good to read, so want to format a bit, this tool has a lot, but I want to get a play.
The first implementation uses a lot of judgment, logic is very round. Later think of reading a template engine before the source code, which used a state diagram, so I also tried to use the next.
public class Main {private static String New_line = "\ r \ n"; public static void Main (string[] args) {String json = "[{\" name\ ": \" wen\ ", \" age\ ": 12,\" flag\ ": True,\" job\ ": [{\ "name\": \ "Java\"},{\ "name\": \ "c++\"}]},{\ "name\": \ "yun\", \ "age\": 13,\ "flag\": false}] "; SYSTEM.OUT.PRINTLN (Format (JSON)); } private static string format (string json) {//Removes the original format json = Json.replace ("\ n", ""). Replace ("\ r", ""). Replace ("\ T", ""); StringBuilder sb = new StringBuilder (); int prevstatus = 0;//on a state int level = 0;//indent hierarchy for (char C:json.tochararray ()) {int oper = g Etoperation (Prevstatus, C); Switch (oper) {case 1:sb.append (new_line). Append (Gettab (level)); Break Case 2:level++; Sb.append (New_line). Append (Gettab (level)); Break Case 3:level--; Sb.append (New_line). Append (Gettab (level)); Break Case 4:sb.append ("); Break } sb.append (c); Prevstatus = GetStatus (c); } return sb.tostring (); }//return: 0 Direct output, 1 line break, 2 increase indent and wrap, 3 decrease Indent and line break, 4 front plus space private static int[][] Statusarr = new int[][] {{0, 0, 0, 0, 0, 3 },//ordinary character {1, 2, 2, 0, 0, 0},//{[{2, 0, 4, 0, 0, 0},//: {3, 1, 4, 0, 0, 0},//, {4, 0, 0, 0, 0, 3},};//}]//action based on previous state and current character private static int getoperation (int status, char c) {return Statu Sarr[status][getstatus (c) + 1]; }//character converted to the corresponding state private static int getStatus (char c) {int status = 0; Switch (c) {case ' {': Case ' [': status = 1; Break Case ': ': status = 2; Break Case ', ': status = 3; Break Case '} ': Case '] ': status = 4; Break } return status; }//indent private static String gettab (int level) {StringBuilder SB = new StringBuilder (); for (int i = 0; I < level; i++) {Sb.append (""); } return sb.tostring (); }}
Execution results
[ { "name": "wen", "age": 12, "flag": true, "job": [ { "name":"java" }, { "name": "c++" } ] }, { "name": "yun", "age": 13, "flag": false }]
JSON string formatting