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);
Related
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
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.
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 made the first request successfully and I like to access my Volley response in other class , how can I do that because when I try to do that it return a null response
use interface and callback
public interface RestCallBack {
void onStart(String action);
void onComplete(String response, String action,Exception e);
}
And in your onResponse
listener.onComplete(response, action, null);
Then you can implement this interface in any class where you want the response.
At first its depends on your json data formate .......
You need to create a class
Declare a method in your class with a parameter string or array and call this method where you get json response
or follow this code
public class MyJsonParser {
public static Vector<MyModel> getJsonResponse(Context context,String response)
throws JSONException, IOException
{
final JSONObject stringResponse = new JSONObject(response);
final JSONObject responseHolder = stringResponse.getJSONObject("data");
final JSONArray jsonArray = responseHolder .getJSONArray("arrayData");
MyModel myModel;
Vector<MyModel> myArray = new Vector<MyModel>();
for (int i= 0;i<jsonArray .length();i++){
myModel= new MyModel();
JSONObject propertyHolder = jsonArray .getJSONObject(i);
myModel.setId(propertyHolder,"id");
myModel.setName(propertyHolder, "name");
myArray .addElement(myModel);
myModel= null;
}
return myArray ;
}
}
and call this method where you get json response like this....
MyJsonParser.getJsonResponse(context,response);
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<ProductData> getAllProductList(#QueryParam("hotel_id") int hotel_id) throws SQLException{
System.out.println("Hotel id id==="+hotel_id);
ProductData productData=new ProductData();
List<ProductData> products = new ArrayList<ProductData>();
rs=stmt.executeQuery("select * from products where hotel_id="+hotel_id);
while(rs.next()){
productData.setProductName(rs.getString("name"));
productData.setProductCategory(rs.getString("category"));
productData.setProductRate(rs.getDouble("rate"));
productData.setProductLogoPath(rs.getString("productLogoPath"));
products.add(productData);
}
return products;
}
I have passed List as JsonObject.Now i tried to get List value like
void handleResponse(String response) throws JSONException {
JSONObject jsonObject=new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("products");
}
but i can't get the List value.anyBody can help me?
There is the simple way to convert json string to object :
Try this :
ObjectMapper mapper = new ObjectMapper();
POJO obj = mapper.readValue(yourJSONString, POJO.class);
Use method signature something similar like-
public Response getAllProduct..
&
return like-
return Response.status(Status.OK).entity(products).build();
For intg. layer use-
public ClientResponse<> similarSignatureMethod..
&
call via the client and then get response entity as-
clientResponse.getEntity();