当前位置: 首页 > 工具软件 > JSONHelper > 使用案例 >

java gson 工具类_Json解析工具类JsonHelper

姜烨伟
2023-12-01

利用Gson快速解析json

需要导入Gson包,解析成一个对象或一个包含此对象的list

JsonHelper代码如下:

import java.util.ArrayList;

import java.util.List;

import android.text.TextUtils;

import com.google.gson.Gson;

import com.google.gson.JsonParseException;

import com.google.gson.JsonParser;

import com.google.gson.reflect.TypeToken;

public class JsonHelper {

private static JsonHelper util;

public static JsonHelper getInstance() {

if (util == null) {

util = new JsonHelper();

}

return util;

}

private JsonHelper() {

super();

}

public String createJsonString(Object value) {

Gson gson = new Gson();

String str = gson.toJson(value);

return str;

}

public T getObject(String jsonString, Class cls) {

T t = null;

try {

if (isGoodJson(jsonString)) {

Gson gson = new Gson();

t = gson.fromJson(jsonString, cls);

}

} catch (Exception e) {

e.printStackTrace();

}

return t;

}

public List getList(String jsonString, TypeToken tt) {

List list = new ArrayList();

try {

if (isGoodJson(jsonString)) {

Gson gson = new Gson();

list = gson.fromJson(jsonString, tt.getType());

}

} catch (Exception e) {

}

return list;

}

public boolean isBadJson(String json) {

return !isGoodJson(json);

}

public boolean isGoodJson(String json) {

if (TextUtils.isEmpty(json)) {

return false;

}

try {

new JsonParser().parse(json);

} catch (JsonParseException e) {

return false;

}

return true;

}

}

使用方法

Bean bean = new Bean();

bean.age="30";

bean.name="name";

String result = JsonHelper.getInstance().createJsonString(bean);

System.out.println(result);

Bean bean2 = JsonHelper.getInstance().getObject(result, Bean.class);

System.out.println(bean2.toString());

ArrayList list = new ArrayList();

list.add(bean);

list.add(bean2);

result = JsonHelper.getInstance().createJsonString(list);

System.out.println(result);

List> list2 = JsonHelper.getInstance().getList(result, new TypeToken>(){});

System.out.println(list2.toString());

Bean.java

public class Bean {

String name="";

String age="";

@Override

public String toString() {

return "Bean [name=" + name + ", age=" + age + "]";

}

}

 类似资料: