import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import net.sf.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.ishopping.common.exception.ErrMessage;
import com.ishopping.common.exception.IShoppingExceptionV2;
/**
* 解析Json协议工具 该工具是基于Google解析引擎之上提供的工具。支持增删改查。
*
* @datetime Aug 13, 20125:35:26 PM
*
*/
public class JsonUtils {
public JsonUtils() {
}
public static JsonElement jsonToElement(String json) {
JsonParser jsonParser = new JsonParser();
return jsonParser.parse(json);
}
private JsonElement jsonElement;
public static JsonUtils getInstance(String json) {
JsonUtils jsonUtils = new JsonUtils();
jsonUtils.jsonElement = jsonToElement(json);
return jsonUtils;
}
public static JsonUtils getInstance() {
return new JsonUtils();
}
public static JsonUtils getInstance(JsonElement jsonElement) {
JsonUtils jsonUtils = new JsonUtils();
jsonUtils.jsonElement = jsonElement;
return jsonUtils;
}
/**
* 解析Json协议字符到Map
* 例如:{command:{\"content\":\"value\",\"test\":100,\"bool\":{\"Test\":true}}}
* 备注:Value只是基本数据类型或Map<String,Object>类型
*
* @param s
* @return
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> parserJsonToMap(String json) {
Map<String, Object> map = new HashMap<String, Object>();
JSONObject jsonObject = JSONObject.fromObject(json);
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
String value = jsonObject.get(key).toString();
if (value.startsWith("{") && value.endsWith("}")) {
map.put(key, parserJsonToMap(value));
} else {
map.put(key, jsonObject.get(key));
}
}
return map;
}
/***************************************************************************
* 解析Json到Map V2,支持潜入基本类型及数组
*
* @param json
* @return
*/
public static Object parserJsonToMapV2(String json) {
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(json);
if (jsonElement.isJsonArray()) {
return parserArrays(jsonElement.getAsJsonArray());
} else if (jsonElement.isJsonNull()) {
return null;
} else if (jsonElement.isJsonObject()) {
return parserJsonObjecet(jsonElement.getAsJsonObject());
} else if (jsonElement.isJsonPrimitive()) {
return jsonElement.getAsString();
}
return null;
}
/**
* 删除元素
*
* @param jsonElement
* @param strs
* @return
*/
public boolean delete(JsonElement jsonElement, String[] strs) {
if (jsonElement.isJsonObject()) {
return delete(jsonElement.getAsJsonObject(), strs);
} else if (jsonElement.isJsonArray()) {
return delete(jsonElement.getAsJsonArray(), strs);
}
return false;
}
public boolean delete(String[] strs) {
if (jsonElement == null)
return false;
if (jsonElement.isJsonObject()) {
return delete(jsonElement.getAsJsonObject(), strs);
} else if (jsonElement.isJsonArray()) {
return delete(jsonElement.getAsJsonArray(), strs);
}
return false;
}
/**
* @param expression格式:key.key.key{层次结构必须一致}
* @return
*/
public boolean delete(String expression) {
if (expression != null) {
return delete(expression.split("\\."));
}
return false;
}
/**
* 添加元素
*
* @param jsonElement
* @param strs
* @param addKey
* @param addValue
* @return
*/
public boolean add(JsonElement jsonElement, String[] strs, String addKey, String addValue) {
if (jsonElement.isJsonObject()) {
return add(jsonElement.getAsJsonObject(), strs, addKey, addValue);
} else if (jsonElement.isJsonArray()) {
return add(jsonElement.getAsJsonArray(), strs, addKey, addValue);
}
return false;
}
public boolean add(JsonElement jsonElement, String expression, String addKey, String addValue) {
if (jsonElement.isJsonObject()) {
return add(jsonElement.getAsJsonObject(),toKeys(expression), addKey, addValue);
} else if (jsonElement.isJsonArray()) {
return add(jsonElement.getAsJsonArray(), toKeys(expression), addKey, addValue);
}
return false;
}
/**
* 添加JsonKey到JsonElement中
* @param strs
* @param addKey
* @param addValue
* @return
*/
public boolean add(String[] strs, String addKey, String addValue) {
if (this.jsonElement == null)
return false;
if (jsonElement.isJsonObject()) {
return add(jsonElement.getAsJsonObject(), strs, addKey, addValue);
} else if (jsonElement.isJsonArray()) {
return add(jsonElement.getAsJsonArray(), strs, addKey, addValue);
}
return false;
}
public boolean add(String expression,String key,String value){
return add(toKeys(expression), key, value);
}
public static void add(JSONObject jsonObject, String key, String value) {
jsonObject.accumulate(key, value).toString();
}
public static JSONObject jsonToJSONObject(String json) {
return JSONObject.fromObject(json);
}
/**
* 更新元素
*
* @param jsonElement
* @param strs
* @param updateKey
* @param updateValue
* @return
*/
public boolean update(JsonElement jsonElement, String[] strs, String updateKey, String updateValue) {
if (jsonElement.isJsonObject()) {
return add(jsonElement.getAsJsonObject(), strs, updateKey, updateValue);
} else if (jsonElement.isJsonArray()) {
return add(jsonElement.getAsJsonArray(), strs, updateKey, updateValue);
}
return false;
}
public boolean update(JsonElement jsonElement, String expression, String updateKey, String updateValue) {
if (jsonElement.isJsonObject()) {
return add(jsonElement.getAsJsonObject(), toKeys(expression), updateKey, updateValue);
} else if (jsonElement.isJsonArray()) {
return add(jsonElement.getAsJsonArray(), toKeys(expression), updateKey, updateValue);
}
return false;
}
/**
* 将字符串key.key.key转化成数组
*
* @param expression
* @return
*/
public static String[] toKeys(String expression) {
return expression.split("\\.");
}
public boolean update(String[] strs, String updateKey, String updateValue) {
if (jsonElement == null)
return false;
if (jsonElement.isJsonObject()) {
return add(jsonElement.getAsJsonObject(), strs, updateKey, updateValue);
} else if (jsonElement.isJsonArray()) {
return add(jsonElement.getAsJsonArray(), strs, updateKey, updateValue);
}
return false;
}
private boolean add(JsonArray jsonArray, String[] strs, String addKey, String addValue) {
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement jsonElement = jsonArray.get(i);
if (jsonElement.isJsonObject()) {
return add(jsonElement.getAsJsonObject(), strs, addKey, addValue);
}
}
return false;
}
/**
* 查询元素
*
* @param jsonElement
* @param strs
* @param searchKey
* @return
*/
public JsonElement search(JsonElement jsonElement, String[] strs) {
if (jsonElement.isJsonObject()) {
return search(jsonElement.getAsJsonObject(), strs);
} else if (jsonElement.isJsonArray()) {
return search(jsonElement.getAsJsonArray(), strs);
}
return null;
}
public JsonElement search(String[] strs) {
if (jsonElement == null)
return null;
if (jsonElement.isJsonObject()) {
return search(jsonElement.getAsJsonObject(), strs);
} else if (jsonElement.isJsonArray()) {
return search(jsonElement.getAsJsonArray(), strs);
}
return null;
}
/**
* 搜索
* @param expression
* 格式:key.key.key{层次结构必须一致}
* @return
*/
public JsonElement search(String expression) {
String[] keys = expression.split("\\.");
return search(keys);
}
private boolean add(JsonObject jsonObject, String[] strs, String addKey, String addValue) {
Set<Entry<String, JsonElement>> set = jsonObject.entrySet();
for (Entry<String, JsonElement> entry : set) {
if (entry.getKey().equals(strs[0])) {// 找到删除对象
if (strs.length == 1) {
JsonElement jsonElement = entry.getValue();
if (jsonElement.isJsonObject()) {
jsonElement.getAsJsonObject().addProperty(addKey, addValue);
return true;
}
}
String[] newStrs = new String[strs.length - 1];
System.arraycopy(strs, 1, newStrs, 0, strs.length - 1);
if (entry.getValue().isJsonArray()) {
return add(entry.getValue().getAsJsonArray(), newStrs, addKey, addValue);
} else if (entry.getValue().isJsonObject()) {
return add(entry.getValue().getAsJsonObject(), newStrs, addKey, addValue);
}
}
}
return false;
}
private JsonElement search(JsonObject jsonObject, String[] strs) {
Set<Entry<String, JsonElement>> set = jsonObject.entrySet();
for (Entry<String, JsonElement> entry : set) {
if (entry.getKey().equals(strs[0])) {// 找到删除对象
if (strs.length == 1) {
return entry.getValue();
}
String[] newStrs = new String[strs.length - 1];
System.arraycopy(strs, 1, newStrs, 0, strs.length - 1);
if (entry.getValue().isJsonArray()) {
return search(entry.getValue().getAsJsonArray(), newStrs);
} else if (entry.getValue().isJsonObject()) {
return search(entry.getValue().getAsJsonObject(), newStrs);
}
}
}
return null;
}
private JsonElement search(JsonArray jsonArray, String[] strs) {
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement jsonElement = jsonArray.get(i);
if (jsonElement.isJsonObject()) {
return search(jsonElement.getAsJsonObject(), strs);
}
}
return null;
}
public static String parserMap(Map<String, Object> map) {
Gson gson = new Gson();
return gson.toJson(map);
}
private static Map<String, Object> parserJsonObjecet(JsonObject jsonObject) {
Map<String, Object> map = new HashMap<String, Object>();
Set<Entry<String, JsonElement>> set = jsonObject.entrySet();
for (Entry<String, JsonElement> entry : set) {
if (entry.getValue().isJsonPrimitive()) {
map.put(entry.getKey(), entry.getValue().getAsString());
} else if (entry.getValue().isJsonNull()) {
map.put(entry.getKey(), "null");
} else if (entry.getValue().isJsonArray()) {
map.put(entry.getKey(), parserArrays(entry.getValue().getAsJsonArray()));
} else if (entry.getValue().isJsonObject()) {
map.put(entry.getKey(), parserJsonObjecet(entry.getValue().getAsJsonObject()));
}
}
return map;
}
private boolean delete(JsonObject jsonObject, String[] strs) {
Set<Entry<String, JsonElement>> set = jsonObject.entrySet();
for (Entry<String, JsonElement> entry : set) {
if (entry.getKey().equals(strs[0])) {// 找到删除对象
if (strs.length == 1) {
return (jsonObject.remove(entry.getKey()) != null);
}
String[] newStrs = new String[strs.length - 1];
System.arraycopy(strs, 1, newStrs, 0, strs.length - 1);
if (entry.getValue().isJsonArray()) {
return delete(entry.getValue().getAsJsonArray(), newStrs);
} else if (entry.getValue().isJsonObject()) {
return delete(entry.getValue().getAsJsonObject(), newStrs);
}
}
}
return false;
}
private boolean delete(JsonArray jsonArray, String[] strs) {
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement jsonElement = jsonArray.get(i);
if (jsonElement.isJsonObject()) {
return delete(jsonElement.getAsJsonObject(), strs);
}
}
return false;
}
private static List<Object> parserArrays(JsonArray jsonArray) {
List<Object> list = new ArrayList<Object>();
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement jsonElement = jsonArray.get(i);
if (jsonElement.isJsonNull()) {
list.add("null");
} else if (jsonElement.isJsonArray()) {
list.add(parserArrays(jsonElement.getAsJsonArray()));
} else if (jsonElement.isJsonObject()) {
list.add(parserJsonObjecet(jsonElement.getAsJsonObject()));
} else if (jsonElement.isJsonPrimitive()) {
list.add(jsonElement.getAsString());
}
}
return list;
}
public JsonElement getJsonElement() {
return jsonElement;
}
public void setJsonElement(JsonElement jsonElement) {
this.jsonElement = jsonElement;
}
/**
* 验证Json数据是否正常
*
* @param keyList
* 必须传递过来的Key
* @return
*/
public List<String> validKeyData(List<String> keyList) {
if (jsonElement == null)
return keyList;
if (jsonElement.isJsonObject()) {
JsonObject jsonObject = jsonElement.getAsJsonObject();
Iterator<Entry<String, JsonElement>> iterator = jsonObject.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, JsonElement> entry = iterator.next();
BK: for (int i = 0; i < keyList.size(); i++) {
if (keyList.get(i).equals(entry.getKey())) {
keyList.remove(i);
break BK;
}
}
}
}
return keyList;
}
/**
* 将多个Key转换成List
*
* @param keys
* @return
*/
public static List<String> toKeyList(String... keys) {
if (keys != null) {
List<String> keyList = new ArrayList<String>(keys.length);
for (int i = 0; i < keys.length; i++) {
keyList.add(keys[i]);
}
return keyList;
}
return null;
}
/**
* 验证协议是否到达预期
*
* @param httpObj
* @param keys
* @param code
* @throws IShoppingExceptionV2
*/
public static void assertValue(HttpObj httpObj, String keys, int code) throws IShoppingExceptionV2 {
JsonElement result = JsonUtils.getInstance(httpObj.getContent()).search(keys);
if (result == null || result.getAsNumber().intValue() != code) {
throw new IShoppingExceptionV2(httpObj, ErrMessage.APPSERVER_ERR);
}
}
}