將Java對(duì)象轉(zhuǎn)換為JSONObject并以GET方法傳輸。
看看Google的Gson。這是一個(gè)非常簡(jiǎn)潔的API,用于將對(duì)象轉(zhuǎn)換為JSON。通過(guò)將類(lèi)中的@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注釋屬性,但是如果最終有任何循環(huán)引用,它將很有用。
祝好運(yùn)。
解決方法 我正在開(kāi)發(fā)一個(gè)Android應(yīng)用程序,為此我還正在開(kāi)發(fā)基于Spring-MVC的服務(wù)器。不幸的是,在此之前,我還沒(méi)有在JSONObjects上做太多工作。目前,我能夠從Android應(yīng)用程序?qū)ava對(duì)象發(fā)送到服務(wù)器,也可以接收J(rèn)ava對(duì)象。 我對(duì)使用Google提供的Volley框架感興趣,該框架將避免Asynctask的麻煩,并且效率更高,但它處理JSONObject。不幸的是,無(wú)論我在網(wǎng)上什么地方,都找到了創(chuàng)建JSOnObjects的代碼,將其保存在本地硬盤(pán)上的某個(gè)文件中,但是不,我想在ResponseBody中傳輸它們,任何人都可以幫助我為JSOBObject創(chuàng)建JAVA對(duì)象反之亦然。我具有所有POM依賴(lài)項(xiàng),并在servlet上下文中設(shè)置了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; }
我希望我的問(wèn)題很清楚,如果有任何疑問(wèn),請(qǐng)告訴我。非常感謝。
相關(guān)文章:
1. mysql - sql 左連接結(jié)果union右連接結(jié)果,導(dǎo)致重復(fù)性計(jì)算怎么解決?2. 網(wǎng)頁(yè)爬蟲(chóng) - python 爬取網(wǎng)站 并解析非json內(nèi)容3. mysql 遠(yuǎn)程連接出錯(cuò)10060,我已經(jīng)設(shè)置了任意主機(jī)了。。。4. 默認(rèn)輸出類(lèi)型為json,如何輸出html5. 數(shù)組排序,并把排序后的值存入到新數(shù)組中6. php多任務(wù)倒計(jì)時(shí)求助7. mysql怎么表示兩個(gè)字段的差8. javascript - 滾動(dòng)到指定高度 開(kāi)始輪流放動(dòng)畫(huà),QQPC官網(wǎng)就是這么做的,請(qǐng)問(wèn)使用什么開(kāi)源庫(kù)方便點(diǎn)?9. PHP訂單派單系統(tǒng)10. MySQL的聯(lián)合查詢(xún)[union]有什么實(shí)際的用處
