/**
* json解析工具
*/
package xx.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JsonUtils {
/**
* 从json字符串解析出键值对
* @param jsonObject json字符串
* @return
*/
public HashMap<String, Object>getValues(String jsonObject){
try {
JSONObject rootJsonObject=new JSONObject(jsonObject);
return getValuesFromJsonObject(rootJsonObject);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
/**
* 解析json键值对
* @param jsonObject
* @return
*/
public HashMap<String, Object> getValuesFromJsonObject(JSONObject jsonObject){
HashMap<String , Object>hashMap=null;
for(Iterator<String> item=jsonObject.keys();item.hasNext();){
String key=item.next();
try {
Object object = jsonObject.get(key);
if(object instanceof JSONArray) {
List<HashMap<String, Object>> maps = getValuesFromJsonArray((JSONArray)object);
if(hashMap==null){
hashMap=new HashMap<String, Object>();
}
hashMap.put(key, maps);
continue;
}else if(object instanceof JSONObject){
HashMap<String, Object> map = getValuesFromJsonObject((JSONObject)object);
if(hashMap==null){
hashMap=new HashMap<String, Object>();
}
hashMap.put(key, map);
continue;
}else{
if(hashMap==null){
hashMap=new HashMap<String, Object>();
}
hashMap.put(key, object);
continue;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return hashMap;
}
/**
* 解析json数组
* @param jsonArray
* @return
*/
public List<HashMap<String, Object>>getValuesFromJsonArray(JSONArray jsonArray){
List<HashMap<String, Object>>hashMaps=null;
for(int i=0;i<jsonArray.length();i++){
try {
JSONObject jsonObject=jsonArray.getJSONObject(i);
HashMap<String, Object> hashMap=getValuesFromJsonObject(jsonObject);
if(hashMaps==null){
hashMaps=new ArrayList<HashMap<String,Object>>();
}
hashMaps.add(hashMap);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return hashMaps;
}
}
android json解析
最新推荐文章于 2024-12-17 06:06:16 发布