首页 > IT职业 > IT职场 > 分享一个json数据的解析类
public class ResolveJsonUtils {
public staticT getJson(String response, Class cls) throws JsonSyntaxException { return new Gson().fromJson(response, cls); } public static T getJson(String response, TypeToken type) throws JsonSyntaxException { return new Gson().fromJson(response, type.getType()); } public static String setJson(Object obj) { return new Gson().toJson(obj); } /** * @param response 需要第一层解析的数据 * @param params 想要解析第一层数据的哪一节点 * @throws JSONException */ public static String getDataJson(String response, String params) throws JSONException { JSONObject jsonObject = new JSONObject(response); // return (String) jsonObject.get(params); return jsonObject.get(params).toString(); } }
// 调用的方法
try {
// 直接解析第一层 user_id是json字符串中的参数名称
user_id = ResolveJsonUtils.getDataJson(response, "user_id");
} catch (JSONException e) {
e.printStackTrace();
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/832/viewspace-2813598/ ,如需转载,请注明出处,否则将追究法律责任。