Converting Java object to JSONObject and transmit it at GET method. - json

I am working on an Android app, for which I am also working on a
Spring-MVC based server. Unfortunately before this, I have not done
that much work on JSONObjects. Currently, I am able to send Java
objects to the server from the Android app, and receive Java objects
too.
I am interested in using the Volley framework provided by Google,
which will avoid the hassle of Asynctask and is more efficient, but
it deals with JSONObject.
Unfortunately wherever I looked on the net, I found the code to
create JSOnObjects to save it in some file on Local Hard drive, but
no, I would like to transmit them in ResponseBody, can anyone help me
out with creating a JAVA object to JSOBObject and vice-versa. I have
all POM dependencies, and messageConvertors set in servlet-context.
Controller code current :
//Restaurant is just a plain Java class, I can give it as a JSONObject, but I dont know how to convert that JSONObject to java so I can save the restaurant in the server.
#RequestMapping(value = "/restaurant/add",method = RequestMethod.POST)
#ResponseBody
public String addRestaurantWebView(#RequestBody Restaurant restaurant){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("restaurant", new Restaurant());
modelAndView.addObject(restaurant);
this.restaurantService.addRestaurant(restaurant);
return "true";
}
//Similarly, here, I don't know how to convert the Restaurant's list to JSONObject when there is a get Request.
#RequestMapping(value = "/restaurant/listing", method = RequestMethod.GET)
public #ResponseBody List<Restaurant> listAllRestaurants(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("restaurant", new Restaurant());
List<Restaurant> restaurantList = this.restaurantService.listRestaurants();
modelAndView.addObject("listRestaurant", restaurantList);
return restaurantList;
}
I hope my question was clear, if there is any doubt, please let me know. Thanks a lot.

Take a look at Google's Gson. It's a pretty concise API for converting objects to JSON. You can easily specify properties by adding the #Expose annotation in your classes to the properties you need to include. Try it like this:
#RequestMapping(value = "/restaurant/listing", method = RequestMethod.GET)
public #ResponseBody String listAllRestaurants(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("restaurant", new Restaurant());
List<Restaurant> restaurantList = this.restaurantService.listRestaurants();
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String jsonString = gson.toJson(restaurantList);
return jsonString;
}
It's not necessary to annotate properties with #Expose but it will help if you end up having any circular references.
Good luck.

Related

How to create a filter using a JSON array in Spring Boot

I am creating a web aplication using Angular 8 for the frontend, and Spring Boot for the backend (I am quite new to SpringBoot programming)
I have a table with a list of "protocols" and a checkbox filter above it. Here is a screenshot of the webpage:
When I click "Apply Filters" button, it generates a JSON array like this:
[{subject_id:[2,3]},{scenario_id:[2]},{algorithms_id:[2]}]
Now, in the backend, I want to create a filter using this JSON array, so that it returns only the corresponding protocols. I guess I have to use a Query functionality and #GetMapping in java SpringBoot. But I don't know how to specify which JSON item to use for each attribute of "protocol". If you could give me some advice on how to do this, I would really appreciate it.
Why not make a Java class - Filter.java with fields :
private List<String> subject_id=new ArrayList<>();
private List<String> scenario_id=new ArrayList<>();
private List<String> algorithms_id=new ArrayList<>();
and then write a POST controller with a RequestBody like:
#RequestMapping(value = "/myapi", method = RequestMethod.POST)
public ResponseEntity<String> getResultsByFilter(
#RequestBody(required = true) List<Filter> filters)
this way you can get the filter in the request body and then process it as per your business logic to return results as you want them.

ResponseEntity : HTTP Status 400 – Bad Request

I have a web service that returns JSON. I am trying to print the screen using this web service spring mvc. The code I wrote is getting 400 errors. How can I resolve it?
I use json object:
{"currencyRates":[{"currencyPair":"BGN/IRR","date":1519922870105,"askPrice":4.376,"bidPrice":2.162},{"currencyPair":"ROL/LKR","date":1519922870105,"askPrice":4.056,"bidPrice":2.132},{"currencyPair":"KES/MGF","date":1519922870105,"askPrice":4.067,"bidPrice":3.005}]}
Controller:
#RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String userList(ModelMap model) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<CurrencyRate>> rateResponse = restTemplate.exchange(
"http://localhost:8080/denemeDenemeDeneme/rates", HttpMethod.GET, null,
new ParameterizedTypeReference<List<CurrencyRate>>() {
});
List<CurrencyRate> rates = rateResponse.getBody();
model.addAttribute("list", rates);
return "list";
}
Thanks...
The problem is that the target class which cannot be a non-static inner class. It doesn't work embedded in the Controller class which I think is the problem.
The details are in here but it boils down to the way Java added inner classes means they don't have the default constructor that Jackson requires.
or Check if your class CurrencyRates does have constructor without any parameter.

JSON RAW REQUEST in controller

I have the code as below
#RequestMapping(method = RequestMethod.POST)
public #ResponseBody ServiceResponse submitCustomerOrder(#RequestBody SubmitCustomerOrderRequest submitCustomerOrderRequest,HttpServletRequest request)
{
String json=????
}
I need the de-serialization should happen to SubmitCustomerOrderRequest object but also need the raw json request in the string for logging the request purpose.
Can anybody help me on this.
Use google's Gson library
log.info(new Gson().toJson(submitCustomerOrderRequest))

JSONObject Alternative in Spring and Jackson

I need to pass a map back to the web application.
I'm used to encapsulating the map in a JSONObject
http://json.org/java/
But since I am using Spring and Jackson Haus.
is there an easier way to maintain the pojo? May I can just annotate the MAP ?
Jackson has com.fasterxml.jackson.core.JsonNode, and specific subtypes like ObjectNode.
These form so-called Tree Model, which is one of 3 ways to handle JSON with Jackson -- some other libraries (like org.json) only offer this way.
So you should be able to just use JsonNode instead; there is little point in using org.json library; it is slow, and has outdated API.
Alternatively you can just use java.util.Map, and return that. Jackson can handle standard Lists, Maps and other JDK types just fine.
If you need to manipulate the output, ie, you don't want to provide all the fields of the object you can use JSonArray:
#RequestMapping(value = "/api/users", method = RequestMethod.GET)
public
#ResponseBody
String listUsersJson(ModelMap model) throws JSONException {
JSONArray userArray = new JSONArray();
for (User user : userRepository.findAll()) {
JSONObject userJSON = new JSONObject();
userJSON.put("id", user.getId());
userJSON.put("firstName", user.getFirstName());
userJSON.put("lastName", user.getLastName());
userJSON.put("email", user.getEmail());
userArray.put(userJSON);
}
return userArray.toString();
}
Use the example from here
Otherwise if you add jackson to your dependencies and set the controller method anotatted with #ResponseBody the response will automatically mapped to JSON. Check here for a simple example.

Can I configure Jackson JSON pretty printing from annotations or from Spring MVC controller?

I'm using Jackson 1.9.6 (codehaus) for JSON serialization of my response bodies in a Spring MVC application, and I'm having trouble finding a way to configure pretty printing. All of the code examples I've been able to find (like this and this) involve playing with an instantiation of ObjectMapper or ObjectWriter, but I don't currently use an instantiation of these for anything else. I wouldn't even know where to put this code. All of my Jackson configurations are taken care of by annotating the POJOs being serialized to JSON.
Is there a way to specify pretty printing in an annotation? I would think they would have put that in #JsonSerialize, but it doesn't look like it.
My class to be serialized looks like this:
#JsonAutoDetect
#JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class JSONObject implements Serializable{...}
and my Spring controller method looks like this:
#RequestMapping(method = RequestMethod.GET)
public #ResponseBody List<Object> getMessagesAndUpdates(HttpServletRequest request, HttpServletResponse response) {
JSONObject jsonResponse = new JSONObject();
.
.
.
//this will generate a non-pretty-printed json response. I want it to be pretty-printed.
return jsonResponse;
}
I searched and searched for something similar and the closest I could find was adding this bean to my Application context configuration (NOTE: I am using Spring Boot so I am not 100% certain this will work as-is in a non-Spring Boot app):
#Bean
public Jackson2ObjectMapperBuilder jacksonBuilder()
{
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.indentOutput(true);
return builder;
}
In my opinion, its the cleanest available solution and works pretty well.
Adding this as a separate answer so I can format the output.
As luck would have it, the non-Spring Boot solution wasn't too far from the Spring Boot solution :)
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
converters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()));
}