Tip: After the article is written, the table of contents can be automatically generated. How to generate it can refer to the help document on the right
Java: JSONObject.toJSONString output string content processing
- foreword
- 1. Remove the double quotes in the JSON string
- 2. When the Date type is output, follow the standard time format
- 3. Remove the default square brackets before and after the JSON stream output
- 4. Remove the nulls that may be contained in the JSON stream output
- Summary, JSON output conforms to the conventional format and does not contain null content
- write at the end
foreword
JSONObject can convert Java objects into JSON stream output, which is very useful for data display or data interaction.
However, the string output by JSONObject.toJSONString often has the following format problems:
1. The String type in Java contains double quotation marks ("") when outputting.
2. The Date type in Java is output as milliseconds (that is, a string Number)
3. When the JSON stream is output, it contains square brackets ("[" "]") by default.
4. The value in Java is empty, and when the JSON stream is output, it is null
This paper presents solutions to these problems.
1. Remove the double quotes in the JSON string
Use String.replaceAll() to remove
Key point: use the escape character \
Code example:
JSONObject.toJSONString(output).replaceAll("\"","")
2. When the Date type is output, follow the standard time format
Use: JSONObject.toJSONStringWithDateFormat()
Key point: the time format can be freely defined as needed
Code example:
JSONObject.toJSONStringWithDateFormat(out,"yyyy-MM-dd HH:mm:ss");
3. Remove the default square brackets before and after the JSON stream output
Use String.replace() to remove
JSONObject.toJSONString(out).replace("[","").replace("]","");
4. Remove the nulls that may be contained in the JSON stream output
Or use String.replace() to remove
JSONObject.toJSONString(out).replace("null","");
Summary, JSON output conforms to the conventional format and does not contain null content
JSONObject.toJSONStringWithDateFormat(out,"yyyy-MM-dd HH:mm:ss").replaceAll("\"","").replace("[","").replace("]","").replace("null","");
write at the end
When JSONObject.toJSONString outputs, it actually outputs a string, and you can use String.replaceAll() to remove any content that you don’t want to see.
The methods introduced in this article are actually stupid methods. You can also use character regular expressions to match , and then remove them according to your needs.
Using character regular expressions to match the code will be much more concise and capable. Friends who are interested can study it.
hope its good for U.S!