How should I output json from JSONArray using jax rs/jersey? [duplicate] - java

This question already has answers here:
Jersey 415 Unsupported Media Type
(3 answers)
Closed 7 years ago.
My restful API method looks like this
#GET
#Produces(MediaType.APPLICATION_JSON)
public JSONArray getMessage()
{
FreeDriversService f=new FreeDriversService();
try {
return f.executeFreeDrivers(); // this method return a JSONArray
}
catch(Exception e) {
System.out.println(e.toString());
return new JSONArray();
}
}
When I use the toString() method on JSONArray it does produce a result, but I would like JSON as output. How can i do that?
I am getting this error
A message body writer for Java class org.json.JSONArray, and Java type class org.json.JSONArray, and MIME media type application/json
was not found

Problem Summary:-
You have mentioned the output as JSON in the #Produces annotation as #Produces(MediaType.APPLICATION_JSON) but instead of sending JSONObject your method getMessage is returning JSONArray.
You can not convert a JSON to an JSONArray simply, because in JSONArray same type of JSONObject can be repeated multiple times with same keys, which can be replaced by the later values of the multiple JSONObject.
Solution :-
You can create a JSONObject and can put the JSONArray inside it as a value for a user defined key.
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getMessage(){
JSONObject finalJson = new JSONObject ();
JSONArray inputArray = new JSONArray();
FreeDriversService f=new FreeDriversService();
try{
inputArray = f.executeFreeDrivers(); // this method return a JSONArray
}catch(Exception e){
System.out.println(e.toString());
}
finalJson.put("array",inputArray );
return Response.status(200).entity(finalJson).build();
}

Related

How to change the key of JSONArray in java

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);

How to use "?" no get Path Rest?

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

How to catch a JSONObject sent via POSTMAN in a Springboot application?

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.

Unable to send Integer value to server using json

I am trying to send following Integer value to server.
int mStoreArea;
I use this link as REST client.
here is Request:
RestClient client = new RestClient(my_url);
client.AddParam("area", String.valueOf(c.getStoreArea()));
and the Error I face is : Int value required!
I retrieve this integer from a json object saved to a file, its procedure is described below:
public myClass(JSONObject json) throws JSONException {
mStoreArea = json.optInt(JSON_TAG);
}
public JSONObject toJSON() throws JSONException {
JSONObject json = new JSONObject();
json.put(JSON_TAG, mStoreArea);
return json;
}
I think you should use this:
client.AddParam("area", Integer.parseInt(c.getStoreArea()));

Convert JSON Object response to JSONP

Returing a JSONObject right now from a restful webservice using Jersey. Its working perfectly fine and returning a JSSONObject as follows.
#GET
#Path("/LoginGetValues")
#Produces({"application/x-javascript"})
public JSONObject GetValues(#QueryParam("request") String request)
{ ...
JSONObject value = new JSONObject();
value = null ;
return value ;
}
But intending to convert that response into JsonP response , tried to append that with a callback function (as the following refering ( here) but then not getting the required response , indeed its asking to define the #JSONP annotation . Also if i have to define the callback then how and where i have to do that ! Kindly help to get a JSONP response
#GET
#JSONP(queryParam="callback")
#Path("/LoginGetValues")
#Produces({"application/x-javascript"})
public JSONWithPadding GetValues( #QueryParam("callback") String callback ,#QueryParam("request") String request)
{ ...
JSONObject value = new JSONObject();
value = null ;
return new JSONWithPadding(value , callback);
}

Categories