import com.alibaba.fastjson.JSONObject; import com.shopcider.plutus.component.exception.Assert; import com.shopcider.plutus.component.exception.BizException; public class JSONUtil { /** * 连续找jsonObject避免空指针原因太难发现 * @param jsonObject * @param keys * @return */ public static JSONObject getJSONObjectByKeys(JSONObject jsonObject, String... keys) { Assert.notEmpty(jsonObject, "jsonObject must not null!"); JSONObject t = jsonObject; Object o; StringBuilder sb = new StringBuilder(); for(String k : keys) { o = t.get(k); if(o == null) { sb.append(k); throw new BizException("找不到对应的key: " + sb.toString() + " 对象: " + jsonObject.toJSONString()); } else if(o instanceof JSONObject == false) { sb.append(k); throw new BizException("key: " + sb.toString() + " 不是ObjectJSON类型而是 " + o.getClass().getName() + " 类型. 对象: " + jsonObject.toJSONString()); } t = (JSONObject) o; sb.append(k); sb.append("."); } return t; } }