Total Pageviews

2017/12/04

Illegal unquoted character ((CTRL-CHAR, code 26)): has to be escaped using backslash to be included in string.

Problem
When I try to convert JSON string to Java bean via Jackson Framework, it throws an exception as bellows: 
Illegal unquoted character ((CTRL-CHAR, code 26)): has to be escaped using backslash to be included in string.

The code snippet is:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package albert.practice.json;

import java.io.IOException;

import org.codehaus.jackson.JsonParser.Feature;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.ObjectMapper;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

public class JSONUtils {

    public Response convertJsonToObject(String json) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Response response = null;
        try {
            response = mapper.readValue(json, Response.class);
        } catch (IOException e) {
            throw e;
        }
        return response;
    }

    @Data
    @ToString
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Response {
        @JsonProperty("Type")
        private String type;
        @JsonProperty("Status")
        private String status;
    }
}




How-To
Owing to the JSON has some CTRL-CHAR, so Jackson Framework cannot covert to Java bean correctly. 
You need to configure OjbectMapper to accept backslash escaping character. The updated code snippet looks like:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package albert.practice.json;

import java.io.IOException;

import org.codehaus.jackson.JsonParser.Feature;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.ObjectMapper;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

public class JSONUtils {

    public Response convertJsonToObject(String json) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
        Response response = null;
        try {
            response = mapper.readValue(json, Response.class);
        } catch (IOException e) {
            throw e;
        }
        return response;
    }

    @Data
    @ToString
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Response {
        @JsonProperty("Type")
        private String type;
        @JsonProperty("Status")
        private String status;
    }
}





No comments: