将 Java 对象转换为 JSONObject 并在 GET 方法中传输。

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

控制器代码当前:

//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;
    }

我希望我的问题很清楚,如果有任何疑问,请告诉我。非常感谢。

看看Google's Gson。将对象转换为 JSON 非常简洁 API。您可以通过将 类 中的 @Expose 注释添加到您需要包含的属性来轻松指定属性。像这样尝试:

@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;
}

没有必要使用@Expose 注释属性,但如果您最终有任何循环引用,它会有所帮助。

祝你好运。