在Spring Boot中将JSON文件作为JSONArray返回

时间:2018-11-29 15:16:03

标签: java json spring-boot

我正在开发一个Spring Boot应用程序,其中有一个JSON属性文件:

{
    data: [
        {"firstWebServiceUrl":"http://localhost:8080/firstUrl/"},
        {"secondWebServiceUrl":"http://localhost:8080/secondUrl/"},
    ]
}

我创建了一个控制器来读取和返回此文件作为org.json.JSONArray对象:

@RestController
@RequestMapping("/Test")
public class MainController {

    @RequestMapping(value = "/getJsonProperties", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public JSONArray getJsonProperties() {
        Resource resource = new ClassPathResource("/static/configs/properties.json");
        InputStream resourceAsStream;
        JSONObject jsonObject = null;
        JSONArray jsonArray = null;
        String resourceAsString = null;
        try {
            resourceAsStream = resource.getInputStream();
            byte[] resourceInBytes = IOUtils.toByteArray(resourceAsStream);
            resourceAsString = new String(resourceInBytes);
            jsonObject = new JSONObject(resourceAsString);          
            jsonArray = jsonObject.getJSONArray("data");
            System.out.println("json array object is " + jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonArray;
    }

}

调用此方法时,我会在控制台中看到输出(感谢sysout):

json array object is [{"firstWebServiceUrl":"http://localhost:8080/firstUrl/"},{"secondWebServiceUrl":"http://localhost:8080/secondUrl/"}]

符合预期。但是,当我通过输入以下网址从浏览器调用此方法:http://localhost:8090/Test/getJsonProperties时,得到的输出是:

{"empty":false}

代替内容。如何退回内容?

1 个答案:

答案 0 :(得分:0)

返回一个字符串而不是JSONArray,因为没有默认转换器可以将JSONArray序列化为JSON字符串:

@RestController
@RequestMapping("/Test")
public class MainController {

    @RequestMapping(value = "/getJsonProperties", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public String getJsonProperties() {
        Resource resource = new ClassPathResource("/static/configs/properties.json");
        InputStream resourceAsStream;
        JSONObject jsonObject = null;
        JSONArray jsonArray = null;
        String resourceAsString = null;
        try {
            resourceAsStream = resource.getInputStream();
            byte[] resourceInBytes = IOUtils.toByteArray(resourceAsStream);
            resourceAsString = new String(resourceInBytes);
            jsonObject = new JSONObject(resourceAsString);          
            jsonArray = jsonObject.getJSONArray("data");
            System.out.println("json array object is " + jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonArray != null ? jsonArray.toString() : "[]";
    }

}