控制器代码当前:
//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;
}
我希望我的问题很明确,如果有任何疑问,请告诉我。非常感谢。
答案 0 :(得分:3)
看看Google's Gson。它是一个非常简洁的API,用于将对象转换为JSON。您可以通过将类中的@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注释属性,但如果您最终有任何循环引用,它将有所帮助。
祝你好运。