import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.CollectionUtils;
/**
* Created by jianghuiwen on 2019/3/11.
*/
public class JsonUtils {
/**
* 比较是否相同
* @param jsona
* @param jsonb
* @return
*/
public static boolean areEqual(JSONObject jsona, JSONObject jsonb) {
if (CollectionUtils.isEmpty(jsona) && CollectionUtils.isEmpty(jsonb)) {
return true;
}
if (CollectionUtils.isEmpty(jsona) && !CollectionUtils.isEmpty(jsonb)) {
return false;
}
if (!CollectionUtils.isEmpty(jsona) && CollectionUtils.isEmpty(jsonb)) {
return false;
}
for (Map.Entry entry : jsona.entrySet()) {
if (jsonb.get(entry.getKey()) == null || !jsonb.get(entry.getKey()).equals(jsona.get(entry.getKey()))) {
return false;
}
}
for (Map.Entry entry : jsonb.entrySet()) {
if (jsona.get(entry.getKey()) == null || !jsona.get(entry.getKey()).equals(jsonb.get(entry.getKey()))) {
return false;
}
}
return true;
}
public static JSONObject mergeAttr(JSONObject oriObject, JSONObject appendObject) {
if (null == oriObject && null == appendObject) {
return new JSONObject();
}
if (null == oriObject) {
return appendObject;
}
if (null == appendObject) {
return oriObject;
}
Set> appendObjectKey = appendObject.entrySet();
for (Map.Entry key : appendObjectKey) {
oriObject.put(key.getKey(), appendObject.get(key.getKey()));
}
return oriObject;
}
/**
* 查出第一个JSON不同于第二个JSON的值
*
* @param oriObject 目标JSON
* @param appendObject 要比较的JSON
* @return
*/
public static JSONObject getDiff(JSONObject oriObject, JSONObject appendObject){
JSONObject diffMetaConfJson = new JSONObject();
if (!CollectionUtils.isEmpty(oriObject)) {
oriObject.forEach((k1, v1) -> {
if (!appendObject.containsKey(k1) || !appendObject.get(k1).equals(
v1)) {
diffMetaConfJson.put(k1, v1);
}
});
}
return diffMetaConfJson;
}
}
用于比较两个JSON是否相同,对空值也做了处理