I am developing a Spring Boot application in which I have a JSON properties file:
{
data: [
{"firstWebServiceUrl":"http://localhost:8080/firstUrl/"},
{"secondWebServiceUrl":"http://localhost:8080/secondUrl/"},
]
}
I have created a controller to read and return this file as org.json.JSONArray
object:
@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;
}
}
When i call this method I see the output in the console (thanks to sysout):
json array object is [{"firstWebServiceUrl":"http://localhost:8080/firstUrl/"},{"secondWebServiceUrl":"http://localhost:8080/secondUrl/"}]
as expected. However when I call this method from the browser by entering the url: http://localhost:8090/Test/getJsonProperties
I get the output:
{"empty":false}
instead of the contents. How can I return the contents?
Return a String instead of JSONArray because there is no default converter that could serialize a JSONArray into a JSON string:
@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() : "[]";
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.