首先,json转map
方法一:
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
或
Gson gson = new Gson();
String strjson 例如:
strjson = { "ret":0, "msg":"", "nickname":"xxx", "figureurl":"http://qzapp.qlogo.cn/qzapp/100226195/C399C7B2880641627CED3EEF9DEB8E30/30", "figureurl_1":"http://qzapp.qlogo.cn/qzapp/100226195/C399C7B2880641627CED3EEF9DEB8E30/50", "figureurl_2":"http://qzapp.qlogo.cn/qzapp/100226195/C399C7B2880641627CED3EEF9DEB8E30/100", "gender":"xxx", "vip":"0", "level":"0", "is_yellow_year_vip":"0" }
Map infoMap = gson.fromJson(strjson, new TypeToken<Map<String, String>>(){}.getType());
方法二:
JSONObject jsonObject = new JSONObject(s);
Map<String,Object> map= new HashMap<String,Object>();
Iterator it = jsonObject.keys();
// 遍历jsonObject数据,添加到Map对象
while (it.hasNext())
{
String key = String.valueOf(it.next());
String value = (String) jsonObject.get(key);
map.put(key, value);
}
return map;
方法三:
JSONObject jasonObject = JSONObject.fromObject(str);
Map<String, Object> map2 = (Map) jasonObject;
但此方法可能不适用, 百度的,出过问题,做个记录。
map转json
JSONObject jsonObject = JSONObject.fromMap(map);
关于jsonArray,留个示例:
public CarDataResultList<CarIntroEntity> parserJson(String paramString) throws Car273Exception { try { JSONObject jsonObj = new JSONObject(paramString); if (jsonObj.has("total")) { defCarIntroList.total = jsonObj.getInt("total"); } if (jsonObj.has("info")) { JSONArray infoArray = jsonObj.getJSONArray("info"); for (int i = 0; i < infoArray.length(); i++) { CarIntroEntity carIntroEntity = new CarIntroEntity(); JSONObject json = infoArray.getJSONObject(i); if (json.has("id")) { carIntroEntity.setId(json.getString("id")); } . . . defCarIntroList.infoList.add(carIntroEntity); } } } catch (JSONException e) { throw ce; }