【问题标题】:Converting Java object to JSONObject and transmit it at GET method.将 Java 对象转换为 JSONObject 并以 GET 方法传输。
【发布时间】:2015-02-25 15:07:59
【问题描述】:
  • 我正在开发一个 Android 应用程序,为此我也在开发一个 基于 Spring-MVC 的服务器。不幸的是,在此之前,我没有做过 在 JSONObjects 上做了很多工作。目前,我可以发送 Java 对象从 Android 应用程序到服务器,并接收 Java 对象 也。
    • 我有兴趣使用谷歌提供的 Volley 框架, 这将避免 Asynctask 的麻烦并且更高效,但是 它处理 JSONObject。
    • 不幸的是,我在网上看到的任何地方,我都找到了代码 创建 JSOnObjects 将其保存在本地硬盘上的某个文件中,但是 不,我想在 ResponseBody 中传输它们,任何人都可以帮助我 将 JAVA 对象创建为 JSOBObject,反之亦然。我有 所有 POM 依赖项,以及在 servlet-context 中设置的 messageConvertors。

控制器代码当前:

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

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

【问题讨论】:

    标签: json spring spring-mvc


    【解决方案1】:

    看看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 注释属性,但如果您最终有任何循环引用,它会有所帮助。

    祝你好运。

    【讨论】:

      猜你喜欢
      • 2016-05-14
      • 1970-01-01
      • 2014-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      相关资源
      最近更新 更多