Json处理工具类 JsonUtil
com.justep.util.JsonUtil 类用于根据 path 返回期望类型的值
getString
getString(JSONObject json, String path)
功能:根据 path 获取对应的值,结果强制转换成 String
参数:
json:需要求值的 JsonObject
path:需要求值的 path
返回:
类型:String
示例:
String jsonStr="{\"store\":{\"book\":[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95,\"no\":8},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99,\"isbn\":\"0-553-21311-3\"}],\"bicycle\":{\"color\":\"red\",\"price\":19.95}}}";
JSONObject json=JSON.parseObject(jsonStr);
String author=JSONUtil.getString(json, "$.store.book[0].author");//Nigel Rees
getInteger
getInteger(JSONObject json, String path)
功能:根据 path 获取对应的值,结果强制转换成 Integer
参数:
json:需要求值的 JsonObject
path:需要求值的 path
返回:
类型:Integer
示例:
String jsonStr="{\"store\":{\"book\":[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95,\"no\":8},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99,\"isbn\":\"0-553-21311-3\"}],\"bicycle\":{\"color\":\"red\",\"price\":19.95}}}";
JSONObject json=JSON.parseObject(jsonStr);
int price=JSONUtil.getInteger(json, "$.store.book[0].no");//8
getJSONObject
getJSONObject(JSONObject json,String path)
功能:根据 path 获取对应的值,结果强制转换成 JsonObject
参数:
json:需要求值的 JsonObject
path:需要求值的 path
返回:
类型:JsonObject
示例:
String jsonStr="{\"store\":{\"book\":[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95,\"no\":8},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99,\"isbn\":\"0-553-21311-3\"}],\"bicycle\":{\"color\":\"red\",\"price\":19.95}}}";
JSONObject json=JSON.parseObject(jsonStr);
JSONObject firstBook=JSONUtil.getJSONObject(json, "$.store.book[0]");//{"no":8,"author":"Nigel Rees","price":8.95,"category":"reference","title":"Sayings of the Century"}
toJSONString
toJSONString(JSONObject json)
功能:将 JSONObject 转换为 JsonString
参数:
json:需要转换的 JsonObject
返回:
类型:JsonString
示例:
String jsonStr="{\"store\":{\"book\":[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95,\"no\":8},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99,\"isbn\":\"0-553-21311-3\"}],\"bicycle\":{\"color\":\"red\",\"price\":19.95}}}";
JSONObject json=JSON.parseObject(jsonStr);
JSONObject firstBook=JSONUtil.getJSONObject(json, "$.store.book[0]");
String firstBookStr=JSONUtil.toJSONString(firstBook);//{"no":8,"author":"Nigel Rees","price":8.95,"category":"reference","title":"Sayings of the Century"}