I am using Java Spring and I am trying to return a JSON object in json format. However my controller below returns a funny HTML format for JSON data, see below.
I want the controller to return the data as JSON formatted data not XML...
Any Ideas?
Thanks,
Pete
Data Returned:
<JSONArray><item><date><date>11</date><hours>15</hours><seconds>52</seconds>
<month>11</month><nanos>0</nanos><timezoneOffset>300</timezoneOffset>
<year>117</year><minutes>32</minutes><time>1513024372000</time><day>1</day>
</date><exception></exception><level>DEBUG</level>
<logger>com.foo.bar.webapp.controller.ReconcileController</logger><id>91</id>
<message>filter was empty</message></item><item><date><date>11</date>
<hours>15</hours><seconds>52</seconds><month>11</month><nanos>0</nanos>
<timezoneOffset>300</timezoneOffset><year>117</year><minutes>32</minutes>
<time>1513024372000</time><day>1</day></date><exception></exception>
<level>DEBUG</level><logger>com.foo.bar.webapp.controller.ReconcileController
</logger><id>92</id><message>returning labels as string</message>
</item><item><date><date>11</date><hours>15</hours><seconds>52</seconds>
<month>11</month><nanos>0</nanos><timezoneOffset>300</timezoneOffset>
<year>117</year><minutes>32</minutes><time>1513024372000</time><day>1</day>
</date><exception></exception><level>DEBUG</level>
<logger>com.foo.bar.webapp.controller.ReconcileController...
Controller Method :
#RequestMapping("/data*")
#Produces("application/json")
#ResponseBody
public JSONArray getData() {
List<LogEntry> logs = logEntryManager.getLogsByDate( new Date() );
JsonConfig config = new JsonConfig();
config.addIgnoreFieldAnnotation(com.fasterxml.jackson.annotation.JsonIgnore.class);
Log.trace("Get LogEntry Data Only");
JSONArray jsonArray = JSONArray.fromObject( logs, config );
return jsonArray;
}
#RequestMapping(value = "data", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON) // import javax.ws.rs.core.MediaType
public #ResponseBody JSONArray getData() {
List<LogEntry> logs = logEntryManager.getLogsByDate( new Date() );
JsonConfig config = new JsonConfig();
config.addIgnoreFieldAnnotation(com.fasterxml.jackson.annotation.JsonIgnore.class);
Log.trace("Get LogEntry Data Only");
JSONArray jsonArray = JSONArray.fromObject( logs, config );
return jsonArray;
}
ignore your #Produces annotation
try this.
Related
JSON received by POST from the front end
[{"id":"001","name":"James"},{"id":"002","name":"Emma"}]
I want to change the key of the received JSON and return it.
[{"ID":"001","FirstName":"James"},{"ID":"002","FirstName":"Emma"}]
#RestController
#RequestMapping("/test")
public class TestController{
#RequestMapping(value="/test1", method=RequestMethod.POST)
public List<Object> post (#RequestBody List<TestDto> list){
JSONArray jArray = new JSONArray(list);
//I want to add a process to change the JSON key here
.......
return jArray.toList();
}
}
I would parse it to a string using
String s = new ObjectMapper().mapper.writeValueAsString(list);
s.replace("id","ID") ;
and return new JSONObject(string);
I am developing a rest server in java, netbeans.
I have my GET request:
//myip/application/v1/cardapio/id=1
#Stateless
#Path("v1/cardapio")
public class CardapioResource {
#GET
#Produces("application/json")
#Path("id={id}")
public String getCardapio(#PathParam("id") int id) {
JsonArray array = (JsonArray) gson.toJsonTree(ejb.findById(id));
JsonObject obj = new JsonObject();
obj.add("dados", array);
return obj.toString();
}
}
It works correctly.
But I want to do differently, as I saw in other examples, I want to mark the beginning of the variables with the "?".
Ex: //myip/application/v1/cardapio/?id=1
#Stateless
#Path("v1/cardapio")
public class CardapioResource {
#GET
#Produces("application/json")
#Path("?id={id}")
public String getCardapio(#PathParam("id") int id) {
JsonArray array = (JsonArray) gson.toJsonTree(ejb.findById(id));
JsonObject obj = new JsonObject();
obj.add("dados", array);
return obj.toString();
}
}
Thus error 404, page not found.
What you seen in "other examples" is just normal usage of URL's query part. Just use it with #Queryparam
#Stateless
#Path("v1/cardapio")
public class CardapioResource {
#GET
#Produces("application/json")
#Path("/") // can be removed actually
public String getCardapio(#QueryParam("id") int id) {
JsonArray array = (JsonArray) gson.toJsonTree(ejb.findById(id));
JsonObject obj = new JsonObject();
obj.add("dados", array);
return obj.toString();
}
}
Here you are mapping getCardapio to v1/cardapio/ and you will try to get id from query string so
Ex: //myip/application/v1/cardapio/?id=1
will just work.
You can't, after ? sign it's query parameters and not path parameters
You can use #QueryParam("id")
You can also use
#RequestParam("id") int id
Following is my controller
#RestController
#RequestMapping("identity/v1/")
public class InvestigateTargetController {
#RequestMapping(method = RequestMethod.POST, value = "receive",
produces = OneplatformMediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<InvestigateOutputResource>
processRequest(#RequestBody JSONObject jsonObject) {
System.out.println(jsonObject.toString());
return new ResponseEntity<>(HttpStatus.OK);
}
}
I am trying to send a json object to this controller via POSTMAN. But when I print jsonObject.toString() the output is {} ( empty ). Following are snapshots of POSTMAN:
Where am I going wrong ?
Create a java class having properties (with getters and setters) same as json object and put it as requestbody.
Solved it. Instead of JSONObject catch it in a string type.
I am newbie, forgive me if this sounds silly.
I am trying to convert a cursor returned by mongo collection into a json object. Such that, when I hit this particular url(localhost:8080/TestReqHere) I receive a list of model object in json format. But the code below does not work as expected.
Note that if i do table.find().toArray() and change the return type to List<DBObject> it works fine. I get a json like response.
#RestController
public class TestController {
#RequestMapping(value = { "/TestReqHere" }, method = RequestMethod.GET)
public List<JSONArray> getTestReqHere( HttpServletResponse response) throws Exception {
JSONArray jsonarray = new JSONArray();
JSONObject jsonobj = new JSONObject();
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("someList");
DBCollection table = db.getCollection("someList");
DBCursor cursor = table.find();
while(cursor.hasNext()) {
BasicDBObject obj = (BasicDBObject) cursor.next();
jsonobj = new JSONObject();
jsonobj.put("col1", obj.getString("col1"));
jsonobj.put("col2", obj.getString("col2"));
jsonobj.put("_id", obj.getString("_id"));
jsonarray.add(jsonobj);
}
return jsonarray;
}
A normal program to convert object to / from JSON using Jackson works fine for me but when run on server I get the below error: Could you please let me know where I am going wrong.
HTTP Status 500 - Could not write content: Class
org.json.simple.JSONObject is not assignable to
org.json.simple.JSONArray (through reference chain:
org.json.simple.JSONArray[0]); nested exception is
com.fasterxml.jackson.databind.JsonMappingException: Class
org.json.simple.JSONObject is not assignable to org.json.simple.JSONArray
(through reference chain: org.json.simple.JSONArray[0])
I am trying to implement REST API endpoints in y application.
#Controller
public class HerokuController {
#RequestMapping(value = "/heroku/resources/", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<JSONObject> provision(#RequestBody JSONObject body){
System.out.println("called! \n");
JSONObject response = new JSONObject();
response.put("id", 555);
response.put("message", "Provision successful!");
return new ResponseEntity<JSONObject>(response,HttpStatus.OK);
}
So I wrote this class containing a method which mapping is (heroku/ressources).
But when I try to call it, I get a 404 error because /WEB-INF/heroku/resources.jsp not found. However, I don't even want to get a view but a HTTP response.
Can anyone tell me which configuration file should we generally modify to tell Spring that this controller doesn't want to send back a view but a HTTP response?
The method is however called if I change it to this :
#RequestMapping(value = "/heroku/resources/", method = RequestMethod.POST)
public ModelAndView provision(final HttpServletRequest request){
System.out.println("called! \n");
JSONObject response = new JSONObject();
response.put("id", 555);
response.put("message", "Provision successful!");
final Map<String, Object> result = new HashMap<String, Object>();
return new ModelAndView("jsonView",result);
}
So changing the return type to "ModelAndView".
thanks.
You are missing the #ResponseBody
#RequestMapping(value = "/heroku/resources/", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody ResponseEntity<JSONObject> provision(#RequestBody JSONObject body){
System.out.println("called! \n");
JSONObject response = new JSONObject();
response.put("id", 555);
response.put("message", "Provision successful!");
return new ResponseEntity<JSONObject>(response,HttpStatus.OK);
}
I had the same problem once, for fix that you can use #RestController instead of #controller (this will send Json by default) and you can definy your method like this
#RequestMapping(value = "/heroku/resources/", method = RequestMethod.POST)
public JsonOut provision(#RequestBody JsonIn json)
I always made my object with the value that i will get from the client, and alway the definition of the output
Ex
public class JsonOut{
protected String id;
protected String message;
...set ....get
}
and you have to put in the spring xml file this two value
<mvc:annotation-driven />
<context:annotation-config/>
With this configuration you will have json always!
This will work with spring 4, i dont know if with spring 3 will work