As you are using spring web framework why not to use jackson for json processing. you can try this way:
@Autowired
ObjectMapper objectMapper;
@Autowired
ResourceLoader resourceLoader;
@GetMapping("/test")
public JsonNode test() throws IOException {
JsonNode node = objectMapper.readValue(resourceLoader.getResource("classpath:/samples/course.json").getURL(), JsonNode.class);
return node;
}
The result of my test:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"application/json"]
Content type = application/json
Body = [{"course":"course1"},{"course":"course1"},{"course":"course1"},{"course":"course1"}]
Forwarded URL = null
Redirected URL = null
Cookies = []
EDIT explanation why JSONObject returns {empty:false}
Spring for json processing uses jackson library. this library doesn't know what is java org.json.JSONObject. so it deals with it as simple POJO that can be serialized with common rules/notations. jackson finds method isEmpty() into JSONObject and as naming of this method looks like POJO getter returns its value. if you want jackson to correctly process org.json.* classes you can use special module from:
https://github.com/FasterXML/jackson-datatype-json-org
and register this module with your objectmapper
bean:
@Bean
Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer( ){
return jacksonObjectMapperBuilder -> {
jacksonObjectMapperBuilder.modules(new JsonOrgModule());
};
}
after this change your orj.json.* objects should be serialized as expected.
P.S.
jackson can serialize map as json so you can also transform your JSONOBject into map. jsonObject.toMap()
and return. this way no extra modules are required.