您的位置:首页 > 编程语言 > Java开发

Gson+JsonPath+泛型 java json解析工具类

2015-11-13 17:37 579 查看
代码下载:点击打开链接

Json解析工具类完善一下,使用GSON+JsonPath+泛型来提高自己写JSON解析的效率 如下关于JsonPath
http://www.7mdm.com/1374.html https://github.com/jayway/JsonPath
为json解析轻松加上Integer Double String List<String> 以及 T List<T>的泛型功能

比如这段json

{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99,
"isbn": "0-553-21311-3"
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}


Java获取所有作者

List<String> list = JsonPathGeneric.getGenericList(json,"$.store.book[*].author", String.class)
输出=====> [Nigel Rees, Evelyn Waugh]

Double d = JsonPathGeneric.getGeneric(json,"$.store.bicycle.price",Double.class);
输出=====>19.95

如果单纯想要获得单本书

public class BeanBook implements Serializable {
public String author;
public Double price;
public String category;
public String title;
@Override
public String toString() {
return "Book [author=" + author + ", price=" + price + ", category="
+ category + ", title=" + title + "]";
}

}


BeanBook bean=JsonPathGeneric.getGenericObject(json,"$.store.book[0]", BeanBook.class);
输出=====>Book [author=Evelyn Waugh, price=12.99, category=fiction, title=Sword of Honour]

除了静态的方法还有指定继承关系的json泛型强转

来一个开发的例子如下
json1

{
"status": "success",
"result": {
"user_id": ​4,
"nickname": "",
"xiaoqu_id": ​1
}
}


json2

{
"status": "success",
"result": [
{
"user_id": ​4,
"nickname": "",
"xiaoqu_id": ​1
},
{
"user_id": 5,
"nickname": "",
"xiaoqu_id": ​3
}
]
}


public class BeanUser {
public String xiaoqu_id  ;
public String user_id  ;
public String nickname  ;
}


java代码

System.out.println(JsonPathGeneric.getGeneric(json1, "$.status", String.class));
{
System.out.println(json1);
String id = new Generic<BeanUser>(json1, "$.result") {
}.getJsonBean().user_id;
System.out.println("user_id=" + id);
}
{
System.out.println(json2);
List<BeanUser> list = new Generic<List<BeanUser>>(json2, "$.result") {
}.getJsonBean();
System.out.println("user_id=" + list.get(1).user_id);
}


打印结果

success
user_id=​4
user_id=5

以下是工具类代码:

package org.utils.json;

import java.lang.reflect.Type;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jayway.jsonpath.JsonPath;

public class JsonPathGeneric<T> {

@SuppressWarnings("unchecked")
public static <T> T getGeneric(String json, String jsonPath, Class<T> clazz) {

return new JsonPathGeneric<T>(clazz, json, jsonPath).getObject();
}

@SuppressWarnings("unchecked")
public static <T> T getGenericObject(String json, String jsonPath,
Class<T> clazz) {
String jsonResult =null;
if(jsonPath==null||"".equals(jsonPath))
{
jsonResult=json;
}else
{
jsonResult = JsonPath.read(json, jsonPath).toString();
}
if (String.class.equals(clazz)) {
return (T) jsonResult;
}
return (T) new Gson().fromJson(jsonResult, clazz);

}

@SuppressWarnings("unchecked")
public static <T> List<T> getGenericList(String json, String jsonPath,
Class<T> clazz) {
String jsonResult =null;
if(jsonPath==null||"".equals(jsonPath))
{
jsonResult=json;
}else
{
jsonResult = JsonPath.read(json, jsonPath).toString();
}

Type listtype = new TypeToken<List<T>>() {
}.getType();
return (List<T>) new Gson().fromJson(jsonResult, listtype);
}

public JsonPathGeneric() {
}

private String json;
private String jsonPath;
private String jsonResult;
private Type type;
private T object;

/**继承关系时注意父类传值*/
public JsonPathGeneric(Object obj, String json, String jsonPath) {
if (obj instanceof Type) {
parse((Type) obj, json, jsonPath);
} else {
parse(ReflectionUtil.getParameterizedTypes(obj)[0], json, jsonPath);
}
}

public JsonPathGeneric(Type type, String json, String jsonPath) {
parse(type, json, jsonPath);
}

public JsonPathGeneric(String json, String jsonPath) {
Type[] parameterizedTypes = ReflectionUtil.getParameterizedTypes(this);
type = parameterizedTypes[0];
parse(type, json, jsonPath);
}

@SuppressWarnings("unchecked")
public void parse(Type type, String json, String jsonPath) {
this.json = json;
this.jsonPath = jsonPath;
this.type = type;
if(jsonPath==null||"".equals(jsonPath))
{
jsonResult=json;
}else{
this.jsonResult = JsonPath.read(json, jsonPath).toString();
}
Class<T> clazz = null;
try {
clazz = (Class<T>) ReflectionUtil.getClass(type);
} catch (ClassNotFoundException e) {
}

if (clazz != null) {
if (String.class.equals(clazz)) {
object = (T) jsonResult;
} else {
object = new Gson().fromJson(jsonResult, clazz);
}
} else {
object = new Gson().fromJson(jsonResult, type);
}
//		System.out.println("-------------------------------");
//		System.err.println(jsonResult);
//		System.err.println(object.getClass().getSimpleName());
//		System.err.println(object);
//		System.out.println("-------------------------------");
}

public String getJson() {
return json;
}

public JsonPathGeneric<T> setJson(String json) {
this.json = json;
return this;
}

public String getJsonPath() {
return jsonPath;
}

public JsonPathGeneric<T> setJsonPath(String jsonPath) {
this.jsonPath = jsonPath;
return this;
}

public String getJsonResult() {
return jsonResult;
}

public Type getType() {
return type;
}

public JsonPathGeneric<T> setType(Type type) {
this.type = type;
return this;
}

public T getObject() {
return object;
}

}


public class Generic<T> {

public Generic(String json, String jsonPath) {
// TODO Auto-generated constructor stub
/**继承关系时注意父类传值this*/
jsonBean = new JsonPathGeneric<T>(this, json, jsonPath).getObject();
}

public T jsonBean;

public T getJsonBean() {
return jsonBean;
}

public void setJsonBean(T jsonBean) {
this.jsonBean = jsonBean;
}

}


代码下载:点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: