Java项目中经常会使用到JSON格式和String格式的数据,所以二者之间的转换也是一个重要的步骤。

Sting类型的数据。如:

转化为JSONObject的步骤如下:

1)、把字符串转成 JSONArray 对象

JSONObject json = JSONObject.fromObject(stringName); 

2)、获取指定数据

获取result:String jsonFlag = json.get("result").toString();

获取msg:JSONArray content = json.getJSONArray("msg"); // 获取msg内容  

3)、遍历数组,封装为JSONObject

JSONObject jo=new JSONObject(); 
JSONArray js=new JSONArray();
if (content.size() > 0) {  
for(int i=0;i<content.size();i++){
   JSONObject jsn=new JSONObject
JSONObject job = content.getJSONObject(i); // 遍历 jsonarray             
jsn.put("visitCount",job.get("visitCount"));//访问总量
            
js.add(jsn);
}
            
}
            jo.put("jo", jsn);

 

posted on 2017-09-07 14:50  浮川之畔  阅读(4226)  评论(0)    收藏  举报