利用递归实现JSON扁平化

1.引入JSON依赖包

把字符串解释成JSON再进行扁平化处理
        
            com.alibaba
            fastjson
            1.2.75
        

2.代码实现

package com.ztesoft;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class JsonParse {

	public static void main(String[] args) {
		String jsonStr = "{\"type\":10,\"data\":[{\"text\":\"献给爱我们的女神\",\"is_liked\":false,\"index_cover\":\"http://photos.breadtrip.com/photo_d_2016_06_19_01_21_20_989_123986672_17737936936133063098.jpg?imageView/2/w/960/q/85\",\"poi\":\"\",\"cover_image_height\":816,\"trip_id\":2387282916,\"index_title\":\"\",\"center_point\":{\"age\":19,\"name\":\"小明\"},\"view_count\":36207,\"location_alias\":\"\",\"cover_image_1600\":\"http://photos.breadtrip.com/photo_d_2016_06_19_01_21_20_926_123986672_17737936923172662193.jpg?imageView/2/w/1384/h/1384/q/85\",\"cover_image_s\":\"http://photos.breadtrip.com/photo_d_2016_06_19_01_21_20_926_123986672_17737936923172662193.jpg?imageView/1/w/280/h/280/q/75\",\"share_url\":\"btrip/spot/2387842143/\",\"timezone\":\"Asia/Shanghai\",\"date_tour\":\"2016-06-19T01:19:07+08:00\",\"is_hiding_location\":false,\"user\":{\"location_name\":\"\",\"name\":\"丑到没墙角\",\"resident_city_id\":\"\",\"mobile\":\"\",\"gender\":2,\"avatar_m\":\"http://photos.breadtrip.com/avatar_41_b8_aedfd71640e3ec09d0c30edc47df04dc56dbf38a.jpg-avatar.m\",\"cover\":\"http://photos.breadtrip.com/default_user_cover_10.jpg-usercover.display\",\"custom_url\":\"\",\"experience\":{\"value\":59,\"level_info\":{\"name\":\"\",\"value\":1}},\"id\":2384288641,\"birthday\":\"\",\"country_num\":null,\"avatar_s\":\"http://photos.breadtrip.com/avatar_41_b8_aedfd71640e3ec09d0c30edc47df04dc56dbf38a.jpg-avatar.s\",\"country_code\":null,\"email_verified\":false,\"is_hunter\":false,\"cdc2\":false,\"avatar_l\":\"http://photos.breadtrip.com/avatar_41_b8_aedfd71640e3ec09d0c30edc47df04dc56dbf38a.jpg-avatar.l\",\"email\":\"\",\"user_desc\":\"\",\"points\":2},\"spot_id\":2387842143,\"is_author\":false,\"cover_image_w640\":\"http://photos.breadtrip.com/photo_d_2016_06_19_01_21_20_926_123986672_17737936923172662193.jpg?imageView/1/w/640/h/480/q/85\",\"region\":{\"primary\":\"\",\"secondary\":\"\"},\"comments_count\":2,\"cover_image\":\"http://photos.breadtrip.com/photo_d_2016_06_19_01_21_20_926_123986672_17737936923172662193.jpg?imageView/2/w/960/q/85\",\"cover_image_width\":1088,\"recommendations_count\":21}],\"desc\":\"\"}";

		Map flatMap = jsonFlattenAsMap(jsonStr);

		for (Map.Entry entry : flatMap.entrySet()) {
			System.out.println(entry.getKey() + " : " + entry.getValue());
		}
	}

	/**
	 * JSON扁平化函数
	 * 
	 * @param jsonStr
	 *            可解释jsonStr字符串
	 * @return 扁平化函数Map
	 */
	public static Map jsonFlattenAsMap(String jsonStr) {

		Object jsonObj = JSON.parse(jsonStr);

		// 有序HashMap
		Map flatMap = new LinkedHashMap(200);

		reduce(flatMap, "", jsonObj);

		return flatMap;
	}

	/**
	 * 递归调用
	 * 
	 * @param flatMap
	 *            结果集
	 * @param key
	 *            当前键
	 * @param jsonObj
	 *            递归对象
	 */
	private static void reduce(Map flatMap, String key, Object jsonObj) {

		// 如果是对象,对JSON对象进行解释
		if (jsonObj instanceof JSONObject) {
			JSONObject parseJsonObj = (JSONObject) jsonObj;

			if (parseJsonObj.isEmpty()) {
				// 如果是空对象,返回空对象
				flatMap.put(key, "{}");

			} else {

				for (Entry entry : parseJsonObj.entrySet()) {
					String entryKey = entry.getKey();
					Object entryValue = entry.getValue();

					String concatKey = !"".equals(key) ? key.concat(".").concat(entryKey) : entryKey;

					if (entryValue instanceof JSONObject) {
						reduce(flatMap, concatKey, entryValue);
					} else if (entryValue instanceof JSONArray) {
						reduce(flatMap, concatKey, entryValue);
					} else {
						// 放置所有连接值
						flatMap.put(concatKey, entryValue);
					}
				}
			}

		} else if (jsonObj instanceof JSONArray) {

			// 如果是数组JSONArray
			JSONArray parseJsonObj = (JSONArray) jsonObj;

			if (parseJsonObj.isEmpty()) {
				// 如果是数组,返回空集
				flatMap.put(key, "[]");

			} else {

				for (int i = 0; i < parseJsonObj.size(); i++) {
					key = key + "[" + i + "]";
					reduce(flatMap, key, parseJsonObj.get(i));
				}
			}

		}

	}

}

3.输出结果

data[0].cover_image_1600 : http://photos.breadtrip.com/photo_d_2016_06_19_01_21_20_926_123986672_17737936923172662193.jpg?imageView/2/w/1384/h/1384/q/85
data[0].timezone : Asia/Shanghai
data[0].cover_image_height : 816
data[0].poi : 
data[0].location_alias : 
data[0].cover_image_s : http://photos.breadtrip.com/photo_d_2016_06_19_01_21_20_926_123986672_17737936923172662193.jpg?imageView/1/w/280/h/280/q/75
data[0].is_hiding_location : false
data[0].is_author : false
data[0].index_cover : http://photos.breadtrip.com/photo_d_2016_06_19_01_21_20_989_123986672_17737936936133063098.jpg?imageView/2/w/960/q/85
data[0].text : 献给爱我们的女神
data[0].cover_image : http://photos.breadtrip.com/photo_d_2016_06_19_01_21_20_926_123986672_17737936923172662193.jpg?imageView/2/w/960/q/85
data[0].is_liked : false
data[0].index_title : 
data[0].trip_id : 2387282916
data[0].date_tour : 2016-06-19T01:19:07+08:00
data[0].spot_id : 2387842143
data[0].recommendations_count : 21
data[0].center_point.name : 小明
data[0].center_point.age : 19
data[0].cover_image_w640 : http://photos.breadtrip.com/photo_d_2016_06_19_01_21_20_926_123986672_17737936923172662193.jpg?imageView/1/w/640/h/480/q/85
data[0].share_url : btrip/spot/2387842143/
data[0].comments_count : 2
data[0].cover_image_width : 1088
data[0].region.secondary : 
data[0].region.primary : 
data[0].user.avatar_m : http://photos.breadtrip.com/avatar_41_b8_aedfd71640e3ec09d0c30edc47df04dc56dbf38a.jpg-avatar.m
data[0].user.birthday : 
data[0].user.avatar_l : http://photos.breadtrip.com/avatar_41_b8_aedfd71640e3ec09d0c30edc47df04dc56dbf38a.jpg-avatar.l
data[0].user.email_verified : false
data[0].user.gender : 2
data[0].user.mobile : 
data[0].user.avatar_s : http://photos.breadtrip.com/avatar_41_b8_aedfd71640e3ec09d0c30edc47df04dc56dbf38a.jpg-avatar.s
data[0].user.experience.level_info.name : 
data[0].user.experience.level_info.value : 1
data[0].user.experience.value : 59
data[0].user.points : 2
data[0].user.cover : http://photos.breadtrip.com/default_user_cover_10.jpg-usercover.display
data[0].user.is_hunter : false
data[0].user.user_desc : 
data[0].user.country_code : null
data[0].user.location_name : 
data[0].user.resident_city_id : 
data[0].user.name : 丑到没墙角
data[0].user.id : 2384288641
data[0].user.cdc2 : false
data[0].user.email : 
data[0].user.custom_url : 
data[0].user.country_num : null
data[0].view_count : 36207
type : 10
desc : 
 

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