基於FastJson封裝的工具類
阿新 • • 發佈:2021-06-19
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 staticJSONObject 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; } }