Code to escape a JSON string in Java

JSON not yet officially supported in Java

For creating large data, I think that the option to use Jackson or Gson is normal, I want to create small data with simple functions without relying on rich libraries. The problem at such times is the string escaping process.

The escape target is

Target character Byte code Escape notation
BS 0x08 \b
HT 0x09 \t
LF 0x0A \n
FF 0x0C \f
CR 0x0D \r
" 0x22 "
/ 0x2F /
\ 0x5C \ \

code

This method replaces character strings byte by byte.

private static String escapeJsonString(CharSequence cs) {
	
	final byte BACKSLASH = 0x5C;
	final byte[] BS = new byte[]{BACKSLASH, 0x62};	/* \\b */
	final byte[] HT = new byte[]{BACKSLASH, 0x74};	/* \\t */
	final byte[] LF = new byte[]{BACKSLASH, 0x6E};	/* \\n */
	final byte[] FF = new byte[]{BACKSLASH, 0x66};	/* \\f */
	final byte[] CR = new byte[]{BACKSLASH, 0x72};	/* \\r */
	
	try (
			ByteArrayOutputStream strm = new ByteArrayOutputStream();
			) {
		
		byte[] bb = cs.toString().getBytes(StandardCharsets.UTF_8);
		
		for (byte b : bb) {
			
			if (b == 0x08 /* BS */) {
				
				strm.write(BS);
				
			} else if (b == 0x09 /* HT */) {
				
				strm.write(HT);
				
			} else if (b == 0x0A /* LF */) {
				
				strm.write(LF);
				
			} else if (b == 0x0C /* FF */) {
				
				strm.write(FF);
				
			} else if (b == 0x0D /* CR */) {
				
				strm.write(CR);
				
			} else if (
					b == 0x22 /* " */
					|| b == 0x2F /* / */
					|| b == BACKSLASH /* \\ */
					) {
				
				strm.write(BACKSLASH);
				strm.write(b);
				
			} else {
				
				strm.write(b);
			}
		}
		
		return new String(strm.toByteArray(), StandardCharsets.UTF_8);
	}
	catch (IOException notHappen) {
		throw new RuntimeException(notHappen);
	}
}

test

public static void main(String[] args) {
		
	String before = "abc \b \t \n \f \r / \\ \"";
	String escaped = escapeJsonString(before);
	System.out.println("{\"value\":\"" + escaped + "\"}");
		
	/* {"value":"abc \b \t \n \f \r \/ \\ \""} */	
}

Recommended Posts

Code to escape a JSON string in Java
Sample code to convert List to List <String> in Java Stream
Convert a Java byte array to a string in hexadecimal notation
How to store a string from ArrayList to String in Java (Personal)
I tried to convert a string to a LocalDate type in Java
Notation to put a variable in a string
All same hash code string in Java
Split a string with ". (Dot)" in Java
Convert to a tag to URL string in Rails
Read a string in a PDF file with Java
Sample code to serialize and deserialize Java Enum enums and JSON in Jackson
How to display a web page in Java
Try to create a bulletin board in Java
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
POST JSON in Java
Create JSON in Java
How to write Java String # getBytes in Kotlin?
I tried to create a Clova skill in Java
How to create a data URI (base64) in Java
I tried to make a login function in Java
How to display a browser preview in VS Code
[Java] How to cut out a character string character by character
[Java] How to erase a specific character from a character string
How to convert A to a and a to A using AND and OR in Java
How to convert a file to a byte array in Java
Try to solve a restricted FizzBuzz problem in Java
Java11: Run Java code in a single file as is
Find a subset in Java
Java in Visual Studio Code
Write Java8-like code in Java8
POST Json in Java ~ HttpURLConnection ~
Json serialization / deserialization in Java 1.4
Code to use when you want to process Json with only standard library in Java
How to use JSON data in WebSocket communication (Java, JavaScript)
How to change a string in an array to a number in Ruby
[Beginner] I made a program to sell cakes in Java
[Java] How to convert a character string from String type to byte type
I just wanted to make a Reactive Property in Java
Create a method to return the tax rate in Java
[Java] How to use substring to cut out a character string
How to select a specified date by code in FSCalendar
Things to be aware of when writing code in Java
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
How to develop and register a Sota app in Java
How to simulate uploading a post-object form to OSS in Java
I tried to make a client of RESAS-API in Java
A memo to start Java programming with VS Code (2020-04 version)
I wrote a code to convert numbers to romaji in TDD
Guess the character code in Java
3 Implement a simple interpreter in Java
Multithreaded to fit in [Java] template
I created a PDF in Java.
How to make a Java container
How to learn JAVA in 7 days
[Java] How to create a folder
Log output to file in Java
Arbitrary string creation code by Java
A simple sample callback in Java
How to use classes in Java?
How to name variables in Java
Try to implement Yubaba in Java