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());}
}