遍历获取JSONObject的所有Key

JSON解析使用JSONObject.keys()可以获取所有的key值,但是这种方法只能获取一层:

比如{"b":"2","c":{"A":"1","B":"2"},"a":"1"},只能够获取b,c,a

如果想要获取被嵌套的{"A":"1","B":"2"}中A,B就不可以了

自己实现了一下获取嵌套类型的JSONObject的所有key值

import java.util.Iterator;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class testGetKeys {

	
	 public static String getKeys(JSONObject test) throws JSONException{
		   
		 String result = null;
		 testJsonCompare t = new testJsonCompare();
		 Iterator keys = test.keys();
		 while(keys.hasNext()){
			 
			 try{
				 
			 String key = keys.next().toString();
			 String value = test.optString(key);
			 
			 int i = t.testIsArrayORObject(value);
			 
			 if(result == null || result.equals("")){
				 if(i == 0){
				
					 result = key + ",";
					 System.out.println("i=0 | key="+key+"| result="+result);
					 
					 
				 }else if( i == 1){
					
					 result = key + ",";
					 System.out.println("i=1 | key="+key+"| result="+result);
					 result = getKeys(new JSONObject(value))+",";
				 }else if( i == 2){
					 
					 result = key + ",";
					 System.out.println("i=2 | key="+key+"| result="+result);
					 JSONArray arrays = new JSONArray(value);
					 for(int k =0;k
testIsArrayORObject是判断一个字符串是array类型还是object
	public int testIsArrayORObject(String sJSON){
		/*
		 * return 0:既不是array也不是object
		 * return 1:是object
		 * return 2 :是Array
		 */
		try {
			JSONArray array = new JSONArray(sJSON);
			return 2;
		} catch (JSONException e) {// 抛错 说明JSON字符不是数组或根本就不是JSON
			try {
				JSONObject object = new JSONObject(sJSON);
				return 1;
			} catch (JSONException e2) {// 抛错 说明JSON字符根本就不是JSON
				System.out.println("非法的JSON字符串");
				return 0;
			}
		}

	}



你可能感兴趣的:(json,java)