JSONQuery使用 Gson 解析 JSON
JSONQuery —— 更簡單的使用 Gson 解析 JSON
解析一個字段只需一行代碼,最多兩行,支持不帶雙引號的非標準JSON
Example:
@Test
public void Test() throws TypeNotMismatchException, FieldNotExistException {
String json = "" +
"{\n" +
" \"errno\": 0,\n" +
" \"errmsg\": 成功,\n" +
" \"user\": \"{\\\"user_id\\\":643361255,\\\"user_name\\\":\\\"鷂之神樂\\\",\\\"user_sex\\\":1,\\\"user_status\\\":1}\",\n" +
" \"comment_info\": [\n" +
" {\n" +
" \"tid\": \"5504460056\",\n" +
" \"pid\": \"116776960983\",\n" +
" \"cid\": \"116857893053\"\n" +
" },\n" +
" {\n" +
" \"tid\": \"5504460056\",\n" +
" \"pid\": \"116776960983\",\n" +
" \"cid\": \"116858057626\"\n" +
" },\n" +
" {\n" +
" \"tid\": \"5504460056\",\n" +
" \"pid\": \"116776960983\",\n" +
" \"cid\": \"116880757453\"\n" +
" }\n" +
" ],\n" +
" \"data\": {\n" +
" \"comment_list\": {\n" +
" \"116776891765\": {\n" +
" \"comment_num\": 3,\n" +
" \"comment_list_num\": 4\n" +
" },\n" +
" \"116776960983\": {\n" +
" \"comment_num\": 4,\n" +
" \"comment_list_num\": 4\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
//獲取根元素errno
JsonResult jsonResult = JSONQuery.select(json, "errno");
//獲取根元素errno,并轉(zhuǎn)換為int
int errno = jsonResult.getAsInt();
//獲取根元素data中的comment_list
jsonResult = JSONQuery.select(json, "data > comment_list");
//正則過濾出屬性數(shù)組,針對一部分拿對象當(dāng)數(shù)組用的情況
jsonResult = JSONQuery.select(json, "data > comment_list > [\\d+]");
//獲取數(shù)組指定位置的元素
jsonResult = JSONQuery.select(json, "comment_info > [2]");
//獲取數(shù)組指定位置的元素 負數(shù)坐標
jsonResult = JSONQuery.select(json, "comment_info > [-1]");
//針對某個字符串屬性的值又是個json字符串的情況
jsonResult = JSONQuery.select(json, "user > user_name");
//jsonResult作為參數(shù)替代json字符串
JsonResult data = JSONQuery.select(json, "data");
jsonResult = JSONQuery.select(data, "comment_list");
//將json字符串轉(zhuǎn)換為JsonResult
jsonResult = JSONQuery.select(json, "");
jsonResult = JSONQuery.select(json, null);
// v0.2.5新增
//將選擇結(jié)果反序列化為普通對象
Post post = JSONQuery.select(json, "comment_info > [2]", Post.class);
//將選擇結(jié)果反序列化為普通對象數(shù)組
Post[] postArray = JSONQuery.select(json, "comment_info", Post[].class);
//將選擇結(jié)果反射為泛型類型ListType type = new TypeToken>() {}.getType();
ListpostList = JSONQuery.select(json, "comment_info", type);
}評論
圖片
表情
