File tree Expand file tree Collapse file tree
main/java/com/baeldung/escape
test/java/com/baeldung/escape Expand file tree Collapse file tree Original file line number Diff line number Diff line change 3333 <groupId >org.json</groupId >
3434 <artifactId >json</artifactId >
3535 <version >20171018</version >
36+ </dependency >
37+ <dependency >
38+ <groupId >com.google.code.gson</groupId >
39+ <artifactId >gson</artifactId >
40+ <version >2.8.5</version >
41+ </dependency >
42+ <dependency >
43+ <groupId >com.fasterxml.jackson.core</groupId >
44+ <artifactId >jackson-databind</artifactId >
45+ <version >2.9.7</version >
3646 </dependency >
3747 <dependency >
3848 <groupId >javax.json.bind</groupId >
Original file line number Diff line number Diff line change 1+ package com .baeldung .escape ;
2+
3+ import com .fasterxml .jackson .core .JsonProcessingException ;
4+ import com .fasterxml .jackson .databind .ObjectMapper ;
5+ import com .google .gson .JsonObject ;
6+ import org .json .JSONObject ;
7+
8+ class JsonEscape {
9+
10+ String escapeJson (String input ) {
11+ JSONObject jsonObject = new JSONObject ();
12+ jsonObject .put ("message" , input );
13+ return jsonObject .toString ();
14+ }
15+
16+ String escapeGson (String input ) {
17+ JsonObject gsonObject = new JsonObject ();
18+ gsonObject .addProperty ("message" , input );
19+ return gsonObject .toString ();
20+ }
21+
22+ String escapeJackson (String input ) throws JsonProcessingException {
23+ return new ObjectMapper ().writeValueAsString (new Payload (input ));
24+ }
25+
26+ static class Payload {
27+ String message ;
28+
29+ Payload (String message ) {
30+ this .message = message ;
31+ }
32+
33+ public String getMessage () {
34+ return message ;
35+ }
36+
37+ public void setMessage (String message ) {
38+ this .message = message ;
39+ }
40+ }
41+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .escape ;
2+
3+ import com .fasterxml .jackson .core .JsonProcessingException ;
4+ import org .junit .jupiter .api .BeforeEach ;
5+ import org .junit .jupiter .api .Test ;
6+
7+ import static org .junit .jupiter .api .Assertions .*;
8+
9+ class JsonEscapeUnitTest {
10+
11+ private JsonEscape testedInstance ;
12+ private static final String EXPECTED = "{\" message\" :\" Hello \\ \" World\\ \" \" }" ;
13+
14+ @ BeforeEach
15+ void setUp () {
16+ testedInstance = new JsonEscape ();
17+ }
18+
19+ @ Test
20+ void escapeJson () {
21+ String actual = testedInstance .escapeJson ("Hello \" World\" " );
22+ assertEquals (EXPECTED , actual );
23+ }
24+
25+ @ Test
26+ void escapeGson () {
27+ String actual = testedInstance .escapeGson ("Hello \" World\" " );
28+ assertEquals (EXPECTED , actual );
29+ }
30+
31+ @ Test
32+ void escapeJackson () throws JsonProcessingException {
33+ String actual = testedInstance .escapeJackson ("Hello \" World\" " );
34+ assertEquals (EXPECTED , actual );
35+ }
36+ }
You can’t perform that action at this time.
0 commit comments