1
  • 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.

We are Borg
  • 5,117
  • 17
  • 102
  • 225

1 Answers1

2

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.

Nick Cromwell
  • 254
  • 2
  • 5