将JsonObject转换成HashMap

1.工具类:

Utils.class:

(1)简单的键值对map

public class Utils {

	public static String getRaw(Context context, int RawId) {

		try {
			InputStream is = context.getResources().openRawResource(RawId);
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));
			// StringBuffer线程安全;StringBuilder线程不安全
			StringBuffer sb = new StringBuffer();
			for (String str = null; (str = reader.readLine()) != null;) {
				sb.append(str);
			}
			return sb.toString();

		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getAsset(Context context, String fileName) {

		try {
			InputStream is = context.getResources().getAssets().open(fileName);
			// StringBuffer线程安全;StringBuilder线程不安全
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));
			StringBuffer sb = new StringBuffer();
			for (String str = null; (str = reader.readLine()) != null;)  {
				sb.append(str);
			}
			return sb.toString();

		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	public static void JsonObject2HashMap(JSONObject jo, List<Map<?, ?>> rstList) {
		for (Iterator<String> keys = jo.keys(); keys.hasNext();) {
			try {
				String key1 = keys.next();
				System.out.println("key1---" + key1 + "------" + jo.get(key1)
						+ (jo.get(key1) instanceof JSONObject) + jo.get(key1)
						+ (jo.get(key1) instanceof JSONArray));
				if (jo.get(key1) instanceof JSONObject) {

					JsonObject2HashMap((JSONObject) jo.get(key1), rstList);
					continue;
				}
				if (jo.get(key1) instanceof JSONArray) {
					JsonArray2HashMap((JSONArray) jo.get(key1), rstList);
					continue;
				}
				System.out.println("key1:" + key1 + "----------jo.get(key1):"
						+ jo.get(key1));
				json2HashMap(key1, jo.get(key1), rstList);

			} catch (JSONException e) {
				e.printStackTrace();
			}

		}

	}
	public static void JsonArray2HashMap(JSONArray joArr,
			List<Map<?, ?>> rstList) {
		for (int i = 0; i < joArr.length(); i++) {
			try {
				if (joArr.get(i) instanceof JSONObject) {

					JsonObject2HashMap((JSONObject) joArr.get(i), rstList);
					continue;
				}
				if (joArr.get(i) instanceof JSONArray) {

					JsonArray2HashMap((JSONArray) joArr.get(i), rstList);
					continue;
				}
				System.out.println("Excepton~~~~~");

			} catch (JSONException e) {
				e.printStackTrace();
			}

		}

	}

	public static void json2HashMap(String key, Object value,
			List<Map<?, ?>> rstList) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put(key, value);
		rstList.add(map);
	}
}

(2)完全Map深层嵌套模式形式:

/**
	 * @param jsonData
	 * @param rstList
	 * @param params
	 * @func hashmap追加字段
	 */
	public static void JsonToHashMap(JSONObject jsonData, Map<String, Object> rstList,
			String... params) {
		try {
			for (Iterator<String> keyStr = jsonData.keys(); keyStr.hasNext();) {

				String key1 = keyStr.next().trim();
				if (jsonData.get(key1) instanceof JSONObject) {
					HashMap<String, Object> mapObj = new HashMap<String, Object>();
					JsonToHashMap((JSONObject) jsonData.get(key1), mapObj, params);
					rstList.put(key1, mapObj);
					continue;
				}
				if (jsonData.get(key1) instanceof JSONArray) {
					ArrayList<Map<String, Object>> arrayList = new ArrayList<Map<String, Object>>();

					JsonToHashMap((JSONArray) jsonData.get(key1), arrayList, params);
					rstList.put(key1, arrayList);
					continue;
				}
				JsonToHashMap(key1, jsonData.get(key1), rstList);
			}
			// 追加字段
			if (params != null && params.length == 2) {
				rstList.put(params[0], params[1]);
			}
			if (params != null && params.length == 4) {
				rstList.put(params[0], params[1]);
				rstList.put(params[2], params[3]);
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	public static void JsonToHashMap(JSONArray jsonarray, List<Map<String, Object>> rstList,
			String... params) {
		try {
			for (int i = 0; i < jsonarray.length(); i++) {
				if (jsonarray.get(i) instanceof JSONObject) {

					HashMap<String, Object> mapObj = new HashMap<String, Object>();
					JsonToHashMap((JSONObject) jsonarray.get(i), mapObj, params);
					rstList.add(mapObj);
					continue;
				}
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	public static void JsonToHashMap(String key, Object value, Map<String, Object> rstList) {
		key = BBSUtils.replaceBlank(key);
		if (value instanceof String) {
			rstList.put(key, BBSUtils.replaceBlank((String) value));
			return;
		}
		rstList.put(key, value);
	}


	public static String getRaw(Context context, int RawId) {

		try {
			InputStream is = context.getResources().openRawResource(RawId);
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));
			// StringBuffer线程安全;StringBuilder线程不安全
			StringBuffer sb = new StringBuffer();
			for (String str = null; (str = reader.readLine()) != null;) {
				sb.append(str);
			}
			return sb.toString();

		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getAsset(Context context, String fileName) {

		try {
			InputStream is = context.getResources().getAssets().open(fileName);
			// StringBuffer线程安全;StringBuilder线程不安全
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));
			StringBuffer sb = new StringBuffer();
			for (String str = reader.readLine(); str != null;) {
				sb.append(str);
			}
			return sb.toString();

		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}
	

备注:

JsonObject里面有两种情况:(1)JsonObject (2)JsonArray 

JsonArray  后面有三种情况:(1)JsonObject (2)JsonArray (3)Object

====================================================

2.调用类:

		String jsonStr = Utils.getRaw(mContext, R.raw.file1);
		String temp = "{\"\":[{\"aa\":\"1\",\"bb\":\"2\"},{\"aa\":\"3\",\"bb\":\"4\"},{\"aa\":\"5\",\"bb\":\"6\"}]}";
		System.out.println("---------jsonStr" + jsonStr);
		ArrayList<Map<?, ?>> rstList = new ArrayList<Map<?, ?>>();

		try {

			Utils.JsonObject2HashMap(new JSONObject(jsonStr), rstList);
			Utils.JsonObject2HashMap(new JSONObject(temp), rstList);
			System.out.println("---------rstList" + rstList);

		} catch (JSONException e) {
			e.printStackTrace();
		}

3.Raw文件夹下文本文件file1:

{
  "programmers": [
    {
      "firstName": "Brett", 
      "lastName": "McLaughlin"
    }, 
    {
      "firstName": "Jason", 
      "lastName": "Hunter"
    }
  ], 
  "authors": [
    {
      "firstName": "Isaac", 
      "lastName": "Asimov"
    }, 
    {
      "firstName": "Tad", 
      "lastName": "Williams"
    }
  ]
}

=================================================================

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
### 回答1: 可以使用Java中的JSONObject类的toMap()方法将JSONObject对象换为HashMap对象,示例代码如下: ``` import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { JSONObject jsonObject = new JSONObject("{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}"); Map<String, Object> map = jsonObject.toMap(); System.out.println(map); } } ``` 输出结果为: ``` {name=John, age=30, city=New York} ``` 注意:如果JSONObject中有嵌套的JSONObjectJSONArray,toMap()方法将会返回嵌套的Map对象,需要进行递归处理。 ### 回答2: JSONObject换为HashMap可以通过遍历JSONObject的键值对,逐个放入HashMap中实现。 具体步骤如下: 1. 首先创建一个空的HashMap对象和JSONObject对象。例如: ``` HashMap<String, Object> hashMap = new HashMap<>(); JSONObject jsonObject = new JSONObject(); ``` 2. 遍历JSONObject的键值对,将键值对逐个放入HashMap中。例如: ``` Iterator<String> keys = jsonObject.keys(); while (keys.hasNext()) { String key = keys.next(); Object value = jsonObject.get(key); hashMap.put(key, value); } ``` 3. 完成换后,HashMap就存在了和JSONObject相同的键值对。使用HashMap进行后续操作即可。 需要注意的是,JSONObject中的值类型可能是其他JSONObjectJSONArray等复杂类型,所以在放入HashMap时可能需要进行递归处理。 以上就是将JSONObject换为HashMap的方法。 ### 回答3: 将JSONObject对象换为HashMap,可以使用如下代码实现: ```java import org.json.JSONObject; import java.util.HashMap; import java.util.Iterator; public class JsonObjectToHashMap { public static void main(String[] args) { // 创建JSONObject对象 JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "John"); jsonObject.put("age", 30); jsonObject.put("city", "New York"); // 创建HashMap对象 HashMap<String, Object> hashMap = new HashMap<>(); // 遍历JSONObject的键值对,并将其添加到HashMap中 Iterator<String> iterator = jsonObject.keys(); while (iterator.hasNext()) { String key = iterator.next(); Object value = jsonObject.get(key); hashMap.put(key, value); } // 打印HashMap System.out.println(hashMap); } } ``` 以上代码首先创建了一个JSONObject对象,并向这个对象中添加了一些键值对。然后,创建一个HashMap对象。接下来,通过迭代JSONObject的键值对,并将其添加到HashMap中。最后,打印HashMap,即可看到JSONObject对象已经成功换为HashMap

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值