Format a JSON data string
Create a project, create a maven project, and introduce the jar package required for parsing JSON. The configuration of pom. xml is as follows:
Net. sf. json-lib
Json-lib
2.4
Jdk15
Parse Java objects
public static void main(String[] args) { int age = 23; Name name = new Name(); name.setFirstName("zhang"); name.setLastName("san"); List
aihao = new ArrayList
(); aihao.add("pashan"); aihao.add("movies"); Person person = new Person(); person.setName(name); person.setAge(age); person.setAihao(aihao); JSONObject jo = JSONObject.fromObject(person); System.out.println(jo.toString()); }
Parse the above object. The console prints the JSON string as follows:
{"age":23,"aihao":["pashan","movies"],"name":{"firstName":"zhang","lastName":"san"}}
String algorithm for formatting JSON objects: traversal of input strings that catch up with characters
1. Get the current character.
2. If the current character is a forward bracket and a forward bracket, do the following:
(1) If there are still characters in front and the character is ":", print: line feed and indent character string.
(2) print: current character.
(3) Front brackets and front curly brackets must be followed by line breaks. Print: line feed.
(4) Each time the front and front curly braces appear, the number of indentation increases. Print: New Line indent.
(5) perform the next loop.
3. If the current character is a trailing bracket and a trailing bracket, do the following:
(1) the backend brackets and backend curly braces must start with a line break. Print: line feed.
(2) Each occurrence of the rear and back curly braces; the number of indentation is reduced once. Print: indent.
(3) print: current character.
(4) If there are still characters after the current character and the character is not ",", print: line feed.
(5) Continue the next cycle.
4. If the current character is a comma. Wrap the line after the comma and indent it without changing the number of indentations.
5. Print: The current character.
Code:
Package com. qidou. dmp. tools;/*** this class provides methods to format JSON strings. * FormatJson format the JSON string to facilitate viewing JSON data. *Example :*
JSON string: ["yht", "xzj", "zwy"] *
Format :*
[*
"Yht ",*
"Xzj ",*
"Zwy "*
] **
The algorithm is as follows :*
Returns the traversal of input strings *
1. Get the current character. *
2. If the current character is a forward bracket and a forward bracket, do the following :*
(1) If there are still characters in front and the character is ":", print: line feed and indent character string. *
(2) print: current character. *
(3) Front brackets and front curly brackets must be followed by line breaks. Print: line feed. *
(4) Each time the front and front curly braces appear, the number of indentation increases. Print: New Line indent. *
(5) perform the next loop. *
3. If the current character is a trailing bracket and a trailing bracket, do the following :*
(1) the backend brackets and backend curly braces must start with a line break. Print: line feed. *
(2) Each occurrence of the rear and back curly braces; the number of indentation is reduced once. Print: indent. *
(3) print: current character. *
(4) If there are still characters after the current character and the character is not ",", print: line feed. *
(5) Continue the next cycle. *
4. If the current character is a comma. Wrap the line after the comma and indent it without changing the number of indentations. *
5. Print: The current character. ** @ Author yanghaitao * @ version [version, January 1, September 29, 2014] */public class JsonFormatTool {/*** unit indent string. */Private static String SPACE = "";/*** returns the formatted JSON String. ** @ Param json unformatted JSON string. * @ Return formatted JSON string. */Public String formatJson (String json) {StringBuffer result = new StringBuffer (); int length = json. length (); int number = 0; char key = 0; // traverses the input string. For (int I = 0; I <length; I ++) {// 1. Obtain the current character. Key = json. charAt (I); // 2. if the current character is a Forward brace and a Forward brace is treated as follows: if (key = '[') | (key = '{') {// (1) if there are still characters in front and the character is ":", print: line feed and indent character string. If (I-1> 0) & (json. charAt (I-1) = ':') {result. append ('\ n'); result. append (indent (number);} // (2) print: current character. Result. append (key); // (3) Front brackets and front curly brackets. The end must be wrapped in a line break. Print: line feed. Result. append ('\ n'); // (4) each time the front and front curly braces appear, the number of indentation increases. Print: New Line indent. Number ++; result. append (indent (number); // (5) for the next loop. Continue;} // 3. if the current character is a trailing bracket and the trailing curly braces, perform the following processing: if (key = ']') | (key = '}') {// (1) rear brackets and rear curly braces. The front must be wrapped in a line break. Print: line feed. Result. append ('\ n'); // (2) each time the backend brackets and backend curly braces appear, the number of indentations is reduced once. Print: indent. Number --; result. append (indent (number); // (3) print: current character. Result. append (key); // (4) if there are still characters after the current character and the character is not ",", print: line feed. If (I + 1) <length) & (json. charAt (I + 1 )! = ',') {Result. append ('\ n');} // (5) Continue the next loop. Continue;} // 4. If the current character is a comma. Wrap the line after the comma and indent it without changing the number of indentations. If (key = ',') {result. append (key); result. append ('\ n'); result. append (indent (number); continue;} // 5. Print: current character. Result. append (key) ;}return result. toString () ;}/ *** returns the indent string of a specified number of times. Three spaces are indented each time, that is, SPACE. ** @ Param number: number of indentations. * @ Return specifies the number of indentations. */Private String indent (int number) {StringBuffer result = new StringBuffer (); for (int I = 0; I <number; I ++) {result. append (SPACE);} return result. toString ();}}
Test cases:
public static void main(String[] args) { JsonFormatTool tool = new JsonFormatTool(); int age = 23; Name name = new Name(); name.setFirstName("zhang"); name.setLastName("san"); List
aihao = new ArrayList
(); aihao.add("pashan"); aihao.add("movies"); Person person = new Person(); person.setName(name); person.setAge(age); person.setAihao(aihao); JSONObject jo = JSONObject.fromObject(person); System.out.println(jo.toString()); System.out.println(tool.formatJson(jo.toString())); }
Output:
{"age":23,"aihao":["pashan","movies"],"name":{"firstName":"zhang","lastName":"san"}}{ "age":23, "aihao": [ "pashan", "movies" ], "name": { "firstName":"zhang", "lastName":"san" }}