lf知识星球banner

遍历获取JSON或是JSONArray对象中指定KEY以及序号的Value

2019-01-08 07:45:00
Seagull
原创
11050

想要一个能获取json或是jsonarray中指定key的value方法,翻了很久的百度,都没有自己想要的,于是借鉴一个网上实现 类似的 代码,改造了一下,达到了想要的目的。


预期目的: 通过传入json字符串,key,key的序号(当一个字符串中有重复时指定,序号从1开始),方法以字符串的形式返回一个对应的key中的value


废话不多说,看代码:


	/**
	 * 初始化返回JSON中Value的值
	 */
	private static String JSONVALUE = "【获取JSON KEY中的Value异常】";
	/**
	 * 用于计数KEY的序号
	 */
	private static int COUNTER = 1;
	/**
	 * 遍历JSON对象
	 * 
	 * @param json
	 * @param key
	 * @param keyindex
	 * @return
	 */
	private static JSONObject parseJsonString(String json, String key, int keyindex) {
		LinkedHashMap<String, Object> jsonMap = JSON.parseObject(json,
				new TypeReference<LinkedHashMap<String, Object>>() {
				}, Feature.OrderedField);
		for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
			parseJsonMap(entry, key, keyindex);
		}
		return new JSONObject(jsonMap);
	}
	/**
	 * 遍历后JSON对象中的key以及value
	 * 
	 * @param entry
	 * @param key
	 * @param keyindex
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private static Map.Entry<String, Object> parseJsonMap(Map.Entry<String, Object> entry, String key, int keyindex) {
		// 如果是单个map继续遍历
		if (entry.getValue() instanceof Map) {
			LinkedHashMap<String, Object> jsonMap = JSON.parseObject(entry.getValue().toString(),
					new TypeReference<LinkedHashMap<String, Object>>() {
					}, Feature.OrderedField);
			for (Map.Entry<String, Object> entry2 : jsonMap.entrySet()) {
				parseJsonMap(entry2, key, keyindex);
			}
		}
		// 如果是list就提取出来
		if (entry.getValue() instanceof List) {
			List list = (List) entry.getValue();
			for (int i = 0; i < list.size(); i++) {
				// 如果还有,循环提取
				list.set(i, parseJsonString(list.get(i).toString(), key, keyindex));
			}
		}
		// 获取key中的value
		if (key.equals(entry.getKey())) {
			if (keyindex == COUNTER) {
				JSONVALUE = entry.getValue().toString();
			}
			COUNTER++;
		}
		return entry;
	}
	/**
	 * 获取JSON或是JSONArray对象指定序号Key中的Value
	 * 
	 * @param json
	 * @param key
	 * @param indexstr
	 * @return
	 */
	public static String getJsonValue(String json, String key, String indexstr) {
		json = json.trim();
		int index = 1;
		String result = JSONVALUE;
		if (isInteger(indexstr) && !"0".equals(indexstr)) {
			index = Integer.valueOf(indexstr);
		} else {
			result = JSONVALUE + "指定的key值序号不是整数或是0(序号从1开始),请检查!";
			return result;
		}
		if (json.startsWith("{") && json.endsWith("}")) {
			try {
				JSONObject jsonStr = JSONObject.parseObject(json, Feature.OrderedField);
				parseJsonString(jsonStr.toString(), key, index);
				result = JSONVALUE;
			} catch (Exception e) {
				result = JSONVALUE + "格式化成JSON异常,请检查参数:" + json;
				return result;
			}
		} else if (json.startsWith("[") && json.endsWith("]")) {
			try {
				// JSONArray jsonarr = JSONArray.parseArray(json);
				// 直接使用fastjson的接口实现有序解析
				JSONArray jsonarr = JSONArray.parseObject(json.getBytes(), JSONArray.class, Feature.OrderedField);
				for (int i = 0; i < jsonarr.size(); i++) {
					JSONObject jsonStr = jsonarr.getJSONObject(i);
					parseJsonString(jsonStr.toJSONString(), key, index);
					if (!JSONVALUE.startsWith("【获取JSON KEY中的Value异常】")) {
						result = JSONVALUE;
						break;
					}
				}
			} catch (Exception e) {
				result = JSONVALUE + "格式化成JSONArray异常,请检查参数:" + json;
				return result;
			}
		} else {
			result = JSONVALUE + "格式化成JSON或是JSONArray时出现异常,请检查参数:" + json;
		}
		if (result.equals("【获取JSON KEY中的Value异常】")) {
			result = JSONVALUE + "没有找到对应的KEY值,请确认!";
		}
		COUNTER = 1;
		JSONVALUE = "【获取JSON KEY中的Value异常】";
		return result;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String jsonstr = "{\"test\":430122198502280330,\"we\":\"dse\",\"boo\":false,\"wqw\":[{\"test\":1239.987,\"we\":\"dse22\",},{\"test\":15439.987,\"we\":\"dse\",}]}";
		String jsonstr2 = "[{\"test\":1239.987,\"we\":\"dse1111\",\"wqw\":[{\"test\":1239.987,\"wea\":{\"test\":15439.987,\"we\":\"dse33333\"}}]}]";
		String key = "test";
		String indexstr = "2";
		System.out.println(getJsonValue(jsonstr, key, indexstr));
	}



文章原创申明
  • 本站文章以及相关内容除注明 转贴外,均为本站 原创翻译

  • 如果本站转载的文章涉嫌侵犯了您的权益,请在评论区留言或是邮件联系管理员及时删除 【admin@luckyframe.cn】

发表评论
评论通过审核后显示。
付费知识圈