首页

基于alibaba的fastjson包定义JsonObjectUtil工具类实现对象字符串及Map间的转换代码示例说明

标签:alibaba,fastjson,JsonObjectUtil,json工具类,对象转字符串,object转JSON,JSON转Map,isEmpty判空     发布时间:2018-10-01   

一、前言

通过alibaba的fastjson包中的com.alibaba.fastjson.JSONArray、com.alibaba.fastjson.JSONObject定义JsonObjectUtil对象工具类,实现object转换成JSON的convertMapToJson、JSON转换成Map的convertJsonToMap、判断JSONObject/JSONArray对象是否为空isEmpty等方法处理,详情参见代码示例说明。

二、代码示例

import java.util.Map; @b@import org.apache.commons.lang.StringUtils;@b@import org.apache.log4j.Logger; @b@import com.alibaba.fastjson.JSON;@b@import com.alibaba.fastjson.JSONArray;@b@import com.alibaba.fastjson.JSONObject;@b@import com.alibaba.fastjson.serializer.SerializerFeature;@b@@b@public class JsonObjectUtil {  @b@@b@	/**@b@	 * object转换成JSON @b@	 * @param object@b@	 * @return@b@	 */@b@	public static String convertMapToJson(Object object) {@b@		if (null == object) {@b@			return null;@b@		}@b@		return JSON.toJSONString(object,@b@				SerializerFeature.DisableCircularReferenceDetect);@b@	}@b@@b@	/**@b@	 * JSON转换成Map @b@	 * @param json@b@	 * @return@b@	 */@b@	public static Map<String, Object> convertJsonToMap(String json) {@b@		if (StringUtils.isBlank(json)) {@b@			return null;@b@		}@b@		JSONArray jsonarray = JSON.parseArray(json);@b@		Map<String, Object> map = null;@b@		if (jsonarray.size() > 1) {@b@			JSONObject jsonObject = jsonarray.getJSONObject(1);@b@			map = (Map<String, Object>) JSONObject.toJavaObject(jsonObject,@b@					Map.class);@b@		}@b@		return map;@b@	}@b@@b@	public static boolean isEmpty(JSONObject json) {@b@		return json == null || json.isEmpty();@b@	}@b@@b@	public static boolean isEmpty(JSONArray array) {@b@		return array == null || array.isEmpty();@b@	}@b@@b@	public static JSONObject getDataResult(JSONObject json) {@b@		JSONObject data = null;@b@@b@		JSONObject tempData = json.getJSONObject("data");@b@		if (tempData == null || tempData.isEmpty()) {@b@			return null;@b@		}@b@@b@		if (tempData.containsKey("data")) {@b@			try {@b@				data = tempData.getJSONObject("data");@b@			} catch (Exception e) { @b@				data = null;@b@			}@b@		}@b@@b@		return data;@b@	}@b@@b@}