i am trying to get json data and store data in db and send json object about status of operation i am able to store data in db but my return json object is not working fine i am not getting json object
my java code:
#RequestMapping(value = "/a",headers="Content-Type=application/json",method = RequestMethod.POST)
#ResponseBody
public JSONObject data(#RequestBody String load)
{
org.json.JSONObject obj = new org.json.JSONObject();
obj.put("Status", "Success");
obj.put("Details","DB updated");
return obj;
}
In your #RequestMapping annotation define produces = MediaTyp.APPLICATION_JSON_VALUE. Your method should then just return a simple Map.
What is returned is actually controlled by the accepts Header in the request. So as an alternativ you could always ensure that your request asks for the right typ. But setting produces in the annotation is in my opinion a good idea as Spring does some auto conversions based on libraries available on the classpath. This might cause security issues if you do not control the type by hand.
edit:
Instead of a simple Map you could also just return any Java Object as long as it can be serialized by Jackson. You can control serialization using annotation in the Object class in this case.
Also you need the Jaclson library on the classpath for this to work (should be the case if you use a basic Spring Boot Web App).
Here is the offical Spring guide on how to build sutch a service: http://spring.io/guides/gs/rest-service/
Related
I would like my controller class to accept different type of RequestBody as part of a POST.
Consider I have an api say /download which is responsible to download bunch of reports (around 30) which has totally different payload. I don't want to create 30 different api's to handle it.
Is there any more simpler way which can be used to avoid this redundancy?
I have tried using below approach:
#RequestMapping(value = "/download", method = RequestMethod.POST)
#ResponseBody
public ResponseEntity download(#RequestBody JsonNode requestBody) {.. }
But, using this approach I am unable to generate API documentation using swagger.
I have a service definition using Spring annotations. Example (source):
#RequestMapping(value = "/ex/foos/{id}", method = GET)
#ResponseBody
public String getFoosBySimplePathWithPathVariable(
#PathVariable("id") long id) {
return "Get a specific Foo with id=" + id;
}
The question is whether spring (or another library) can auto-create a remote implementation (client) of the same API without the need to manually type paths, method type, param names, etc. (like needed when using RestTemplate)?
Example of an such a client usage:
FooClient fooClient = new FooClient("http://localhost:8080");
String foo = fooClient.getFoosBySimplePathWithPathVariable(3l);
How can I get to such a client "generated" implementation"?
You are probably looking for Feign Client. It does everything you need: calling one service via HTTP is similar to calling method of Java interface. But to make it work you need Spring Cloud, standard Spring framework doesn't have this feature yet.
You can generate it using Swagger Editor. You shoud just define the path of the resources and then it'll generate for you the client for almost any language of your choice
Newbie question...
I'm building my first Spring Boot restful service and want to support a GET call that returns a collection of entities. like:
/api/customers/
However, for certain consumers -like a list page in a web UI - they would only need a subset of the customer entity properties.
I'm thinking that I could add request parameters to my GET call to set the consumers specific field requirements, like
/api/customers/?fields=id,name,address
But what's the best way of implementing this inside the Java restful controller?
Currently in my rest controller the 'GET' is request mapped to a Java method, like
#RequestMapping(value="/", method= RequestMethod.GET)
public Customer[] getList() {
Customer[] anArray = new Customer[];
....
return anArray;
}
Is it possible to somehow intervene with the default Java to Json response body translation so that only the required properties are included?
TIA
Adding fields parameter is a good idea, best practice according to http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api#limiting-fields
How to leave fields out?
1) Set them to null, possibly in a dedicated output class annotated with #JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
Or
2) Use SimpleBeanPropertyFilter See a good step by step tutorial here 5. Ignore Fields Using Filters
I'm using Vertx 3, and I'm trying to find a good decoupled module that knows to turn query-string, headers and both content-type and body into a bean?
I know spring does that and various other frameworks as well, but I don't want to introduce a new framework i just want a super fast model binder that will either know to auto bind to a certain method or at least auto bind a certain class so i can invoke my rest method that currently accept one parameter, which is the model.
public ResponseBase query(QueryRequest model){ ... }
I don't mind adding annotations to the parameters etc.
Thanks!
Current my team use vertx Json.decodeValue to turn body (json string) to java class.
MyClass body = Json.decodeValue(rc.getBodyAsString(), MyClass.class);
to config Json to handle unknown properties, I setting
Json.mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
for your query string, I think it is easy to write a class to convert it to a json string :)
I also catch DecodeException on Json.decodeValue to re throw a 400 Bad Request error.
Currently I have a web service running in a tomcat (http://localhost:8080/myApp/getUsers). My web service will accept a json string and then process accordingly. My webservice code is as follows:
#Path("/getUsers")
public class UsersWS
{
#POST
public Response post(String theRequestJSON)
{
try
{
JSONObject aJsonObj = new JSONObject(theRequestJSON);
String userID = aJsonObj.getString("userID");
System.out.println(userID);
}
}
}
So, my Web service is processing a json string. So now, I need to call the above web service from another JAVA class (with a jsonObject having the userID in request parameter).
How to do it? Shortly, I need to make a web service call from a JAVA class with a JSON object as a request parameter. How to send a json as a request parameter in a request call.
Take a look at Jersey: http://jersey.java.net
Here's a good write up on how to use the client:
http://blogs.oracle.com/enterprisetechtips/entry/consuming_restful_web_services_with
Use native URLConnection or Apache HttpClient to send a HTTP request to the server.And the parameters must passed in key=value&key2=value2... format. So you may need to reconstruct the JSON object in that format or using another special parameter name like data=jsonstring then parse the json string using some library.
#George has basically already answered your question, but in terms of JSON processing you may want to also look at Jackson http://jackson.codehaus.org/
This allows you to quickly convert Java objects to JSON equivalents.