最近工做中,常常须要对json作解析,而json的格式又不统一,实际使用也就是获取json中的一个节点值。因而就想经过写json路径的方式来直接拿到节点值,这样就就不用对不一样格式的json数据单独写解析方法了。下面这段代码可以很好的解决这个问题,给对于和我有一样需求的童鞋作个参考。另外对于接口测试,在个人phoenixframework平台中的phoenix_interface里面还有不少诸如此类的工具,会给开发工做带来很大的方便。java
import java.util.HashMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class JsonPaser { /** * 对节点进行解析 * * @author mengfeiyang * @param obj * @param node * @return */ private static JSONObject getObj(JSONObject obj, String node) { try { if (node.contains("[")) { JSONArray arr = obj.getJSONArray(node.substring(0,node.indexOf("["))); for (int i = 0; i < arr.length(); i++) { if ((i + "").equals(node.substring(node.indexOf("["),node.indexOf("]")).replace("[", ""))) { return arr.getJSONObject(i); } } } else { return obj.getJSONObject(node); } } catch (Exception e) { return obj; } return null; } /** * 获取节点值 * @author mengfeiyang * @param jsonContent * @param jsonPath * @return * @throws Exception */ public static synchronized String getNodeValue(String jsonContent, String jsonPath) throws Exception { String[] nodes = jsonPath.split("\\."); JSONObject obj = new JSONObject(jsonContent); for (int i = 1; i < nodes.length; i++) { if (obj != null) { obj = getObj(obj, nodes[i]); } if ((i + 1) == nodes.length) { try{ return obj.getString(nodes[i]); }catch(Exception e){ return "JSONException:"+e.getMessage()+",NodeString:"+obj.toString(); } } } return null; } public static void main(String[] args) throws Exception { //构造json字符串 String jsonContent = "{\"projectName\":\"JSON\",\"projectInfo\":{\"author\":\"test\",\"version\":1.0}}"; String val = JsonPaser.getNodeValue(jsonContent, "JSON.projectInfo.author"); System.out.println(val);//执行结果:test } }
如上代码中json字符串的树结构以下:node
获取author的json路径就是:JSON.projectInfo.author,是否是方便了不少呢。chrome
在实际使用时,这样的json路径很容易得到,例如经过chrome的json插件。json