本文目錄一覽:
怎麼把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());
怎麼把json字元串轉換map?
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import net.sf.json.JSONObject;
public MapString, String toMap(Object object)
{MapString, String data = new HashMapString, String();
// 將json字元串轉換成jsonObject
JSONObject jsonObject = JSONObject.fromObject(object);
Iterator ite = jsonObject.keys();
// 遍歷jsonObject數據,添加到Map對象
while (ite.hasNext())
{String key = ite.next().toString();
String value = jsonObject.get(key).toString();
data.put(key, value);
// 或者直接將 jsonObject賦值給Map
// data = jsonObject;
return data;
}
JAVA中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.
JAVA中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-tw/n/192479.html