Gson详解(二)
1.復雜Json轉成對象
比如:jsonString:{“response”:{“content”:"\n\t",“msg”:“成功”,“code”:“0”,“data{“content”:”\n\t",“VIN”:“LDC12345678901234”},“cmd”:“ScanVINCode”}}
Gson解析
Gson gson = new Gson();roodBean = gson.fromJson(jsonString, VinBean.class);if (roodBean != null) {responseBean = roodBean.getResponse();if (responseBean != null) {dataBean = responseBean.getData();if (dataBean != null) {tvReciveData.setText("獲取" + responseBean.getMsg() + "\nvin:" + dataBean.getVIN());}}}VinBean
/*** Description:Vin號的Bean類* AUTHOR: Champion Dragon* created at 2019/7/9**/ public class VinBean {/* json字符串: formatted:{"response": {"content": "\n\t","msg": "成功","code": "0","data": {"content": "\n\t","VIN": "LDC12345678901234"},"cmd": "ScanVINCode"}}*/private ResponseBean response;public ResponseBean getResponse() {return response;}public void setResponse(ResponseBean response) {this.response = response;}/*** content :* msg : 成功* code : 0* data : {"content":"\n\t","VIN":"LDC12345678901234"}* cmd : ScanVINCode*/public static class ResponseBean {private String content;private String msg;private String code;private DataBean data;private String cmd;public String getContent() {return content;}public void setContent(String content) {this.content = content;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}public DataBean getData() {return data;}public void setData(DataBean data) {this.data = data;}public String getCmd() {return cmd;}public void setCmd(String cmd) {this.cmd = cmd;}/*** content :* VIN : LDC12345678901234*/public static class DataBean {private String content;private String VIN;public String getContent() {return content;}public void setContent(String content) {this.content = content;}public String getVIN() {return VIN;}public void setVIN(String VIN) {this.VIN = VIN;}}} }2.json數組轉Gson
"muser": [{"name": "zhangsan","age": "10","phone": "11111","email": "11111@11.com"},...]2.1JsonArray遍歷
//Json的解析類對象 JsonParser parser = new JsonParser(); //將JSON的String 轉成一個JsonArray對象 JsonArray jsonArray = parser.parse(strByJson).getAsJsonArray();Gson gson = new Gson(); ArrayList userBeanList = new ArrayList<>();//加強for循環遍歷JsonArray for (JsonElement user : jsonArray) { //使用GSON,直接轉成Bean對象 UserBean userBean = gson.fromJson(user, UserBean.class); userBeanList.add(userBean);2.2直接轉成list對象數組
解析的數組字符串外面多一個大括號 response
{ [{"jylsh": "HZTYQ20180119074","hphm": "浙A5J592","hpzl": "大型汽車","jycs": "1","jyxm": "F1,F4","sqsj": "20180119154701","hpzlcode": "01"},{"jylsh": "HZTYQ20180130054","hphm": "浙A3183","hpzl": "警用汽車","jycs": "2","jyxm": "F4","sqsj": "20180130134051","hpzlcode": "23"},{"jylsh": "20180204151749","hphm": "浙AQ90K3","hpzl": "小型汽車","jycs": "","jyxm": "F4","sqsj": "20180204151749","hpzlcode": "02"}] } CarListResponsebean carListResponsebean = GsonUtils.fromJson(response, CarListResponsebean.class); List<CarListItemBean> data = carListResponsebean.getData();2.3通過Gson中TypeToken轉成list對象
解析的數組字符串外面少一個大括號
[{"name":"Tom","age":"10"}, {"name":"Lucy","age":"11"}, {"name":"Lily","age":"11"}] List<Person> people = gson.fromJson(jsonData, new TypeToken<List<Person>>(){}.getType());三.GsonUtils工具類
public class GsonUtil {private static final Gson GSON = createGson(true);private static final Gson GSON_NO_NULLS = createGson(false);private GsonUtil() {throw new UnsupportedOperationException("u can't instantiate me...");}/*** 創建Gson對象*/private static Gson createGson(final boolean serializeNulls) {final GsonBuilder builder = new GsonBuilder();if (serializeNulls) {builder.serializeNulls();//是否序列化空值} //打開Export注解,但打開了這個注解,副作用,要轉換和不轉換都要加注解(造成json轉換失敗)一般千萬別用builder.excludeFieldsWithoutExposeAnnotation().setDateFormat("yyyy-MM-dd HH:mm:ss")//序列化日期格式 "yyyy-MM-dd"//.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)//會把字段首字母大寫 //需要結合注解使用,有的字段在1.0的版本的時候解析,但0.1版本不解析 // .setVersion(1.0) .setPrettyPrinting(); //自動格式化換行return builder.create();}//獲取gson解析器public static Gson getGson() {return getGson(true);}/*** 是否序列化空值*/public static Gson getGson(final boolean serializeNulls) {return serializeNulls ? GSON_NO_NULLS : GSON;}//對象轉換為jsonpublic static String toJson(Object object) {return toJson(object, true);}public static String toJson(final Object object, final boolean includeNulls) {return includeNulls ? GSON.toJson(object) : GSON_NO_NULLS.toJson(object);}//JSON轉換為對象1--普通類型public static <T> T fromJson(String json, Class<T> classOfT) {return GSON.fromJson(json, classOfT);}//JSON轉換為對象-針對泛型的類型public static <T> T fromJson(String json, Type typeOfT) {return GSON.fromJson(json, typeOfT);}public static <T> T fromJson(final Reader reader, final Class<T> type) {return GSON.fromJson(reader, type);}public static <T> T fromJson(final Reader reader, final Type type) {return GSON.fromJson(reader, type);}/*** @param reader JsonReader(位于Gson包中) *InputStreamReader inputStreamReader = new InputStreamReader(inputStream);* JsonReader jsonReader = new JsonReader(inputStreamReader);* @param type json將要轉換的類型* @return T 實例類型**/public static <T> T fromJson(final JsonReader reader, final Type type) {return GSON.fromJson(reader, type);}/*** 轉成list,解決泛型在編譯期類型被擦除導致報錯*/public static <T> List<T> jsonToList(String json, Class<T> cls) {List<T> list = new ArrayList<T>();JsonArray array = new JsonParser().parse(json).getAsJsonArray();for (final JsonElement elem : array) {list.add(GSON.fromJson(elem, cls));}return list;}/*** 轉成list中有map的*/public static <T> List<Map<String, T>> GsonToListMaps(String gsonString) {return GSON.fromJson(gsonString, new TypeToken<List<Map<String, T>>>() {}.getType());}/*** 轉成map的*/public static <T> Map<String, T> GsonToMaps(String gsonString) {return GSON.fromJson(gsonString, new TypeToken<Map<String, T>>() {}.getType());} }總結
- 上一篇: linux内核杂记(10)-进程调度(5
- 下一篇: 操作系统设计与实现第3版笔记与minix