本文目錄一覽:
怎麼把json字符串轉換成map
在升級QQ登錄到OAuth2.0時,其返回的是一個json形式的字符串,將其轉換成Map
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
或
Gson gson = new Gson();
String json 如下;
{ “ret”:0, “msg”:””, “nickname”:”xxx”, “figureurl”:””, “figureurl_1″:””, “figureurl_2″:””, “gender”:”xxx”, “vip”:”0″, “level”:”0″, “is_yellow_year_vip”:”0″ }
Map infoMap = gson.fromJson(json, new TypeTokenMapString, String(){}.getType());
JsonObject轉成Map?
首先,你先確認你的字符串是否是json格式的,如果是json格式,那你可以使用Gson.jar或json-lib-xx-jdk.jar兩個包來自動解析解析。
使用Gson更簡單些,只需要導入一個包就可以,但是他如果使用Object解析到int型的話或自動轉成double型,需要定義一個準確的類來解析,不能直接使用Object。示例:
Gson gson = new Gson();
MapString, Object map = new HashMapString, Object();
map = gson.fromJson(str, map.getClass());
GSON.jar包的下載地址:
使用json-lib包的話需要導入更多的包,需要額外導入commons-lang.jar、ezmorph-1.0.4.jar、commons-logging-1.1.1.jar、commons-collections.jar、commons-beanutils.jar這5個包。解析示例如下:
JSONObject jb = JSONObject.fromObject(str);
MapString, Object map = (MapString, Object)jb;
如果你的字符串不是json格式,那你就需要自己使用split分割字符串,例如:
String str = “color:red|font:yahei|width:800|height:300”;
String[] strs = str.split(“\\|”);
MapString, String m = new HashMapString, String();
for(String s:strs){
String[] ms = s.split(“:”);
m.put(ms[0], ms[1]);
}
JSONObject json = JSONObejct.fromObject(map)
上面的方法轉出來的結果為map的key.toString()和value.toString() 的結果對。
SomeClass 是你的自定義類,你沒有重寫toString方法,默認調用的是Object類的toString方法。
你重寫下SomeClass 的toString方法,輸出你想要的結果,然後,轉出來的JSON就不再是內存地址了
如何將返回的JSon字符串用MAP格式讀取
我們需要先把json字符串轉化為net.sf.json.JSONObject對象,java中這樣就可以完成json字符串到Map的轉換了。
1.將數組轉換為JSON:String[] arr = {“asd”,”dfgd”,”asd”,”234″};JSONArray jsonarray = JSONArray.fromObject(arr);System.out.println(jsonarray);
2.對象轉換成JSON:UserInfo user = new UserInfo(1001,”張三”);JSONArray jsonArray = JSONArray.fromObject(user);System.out.println( jsonArray );
3.把Map轉換成json, 要使用jsonObject對象:MapString, Object map = new HashMapString, Object();map.put(“userId”, 1001);map.put(“userName”, “張三”);map.put(“userSex”, “男”);JSONObject jsonObject = JSONObject.fromObject(map);System.out.println(jsonObject);
4.把List轉換成JSON數據:ListUserInfo list = new ArrayListUserInfo();UserInfo user = new UserInfo(1001, “張三”);list.add(user);list.add(user);list.add(user);JSONArray jsonArray = JSONArray.fromObject(list);System.out.println(jsonArray);
5.
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/230393.html