码迷,mamicode.com
首页 > Web开发 > 详细

json、map互转

时间:2015-01-27 18:13:36      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:

首先,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; }

 

技术分享

json、map互转

标签:

原文地址:http://www.cnblogs.com/ws5861/p/4253530.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!