如何摆脱JSON响应中显示的转义字符?

时间:2018-04-20 03:53:43

标签: java json rest spring-boot

我有一个springBoot(版本2.0.0)应用程序,它从资源路径读取一个json文件,并返回一个返回文件内容的GET方法。

以下是我的json文件,存储在src / main / resources下。

{"name":"fileName","fields":[{"fields":{"fieldO":[{"id":"label1","name":"name1"}]}}]}

这是读取文件的类。

@Component
public class ReadFile {

public String read(String path) throws IOException, JSONException {

    String jsonString = null;

    ClassPathResource classPathResource = new ClassPathResource(path);
    try (InputStream inputStream = classPathResource.getInputStream()) {
        // Create the JSON String
        StringBuilder json = new StringBuilder();
        try (Reader reader = new BufferedReader(
                new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
            int c = 0;
            while ((c = reader.read()) != -1) {
                json.append((char) c);
            }
            jsonString = json.toString();
            System.out.println(jsonString);

        }
    }
    return jsonString;
  }

}

以下是我的REST控制器。

@RestController
public class MyController {

@Autowired
ReadFile readFile;

private static final String PATH = "/myFile.json";
public class FinalValue {
    private Object file;
    private Object data;
    public Object getFile() {
        return file;
    }
    public void setFile(Object file) {
        this.file = file;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }   
}

@GetMapping(path = "/file", produces = "application/json; charset=UTF-8")
public ResponseEntity<FinalValue> getFile() throws JSONException, IOException {
    Object obj = readFile.read(PATH);
    if (obj == null) {
        System.out.println("ReadFile is null");
        return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
    } else {
        FinalValue fv = new FinalValue();
        fv.setData("No User Data");
        fv.setFile(obj);
        return new ResponseEntity<>(fv, HttpStatus.OK);
    }
}

}

当我从邮递员或浏览器尝试GET网址时,我的回复类似于以下内容:

{
"file": "{\"name\":\"fileName\",\"fields\":[{\"fields\":{\"fieldO\":[{\"id\":\"label1\",\"name\":\"name1\"}]}}]}",
"data": "No User Data"
}

我不允许更改json文件的结构。如何处理此文件以消除响应中的转义字符?

0 个答案:

没有答案