Gson是谷歌官方推出的支持 JSON -- Java Object
相互转换的 Java序列化/反序列化
库
本菜鸟用的是Android Studio
一:添加到项目中
app下build.gradle
dependencies {
implementation 'com.google.code.gson:gson:2.8.4'
}
二:简单的序列化(***转为json数据)/反序列化(json数据转为***)
toJson(***):将***对象转化为Json数据
fromJson(str,javaBean.class);将Json数据str转化为javaBean
接下来看实列:
private int[] imageUrl = {R.mipmap.linjunjie,R.mipmap.liudehua,R.mipmap.liyugang,R.mipmap.wamgfei,R.mipmap.xusong,
R.mipmap.yangyuying,R.mipmap.zhangguorong,R.mipmap.zhangjie,R.mipmap.zhangliangyin,R.mipmap.zhoujielun};
private String[] musicName = {"林俊杰","刘德华","李玉刚","王菲","许嵩","杨钰莹","张国荣","张杰","张靓颖","周杰伦"};
/*
* 1:准备数据
* 2:写JavaBean
* 3:将数据填充到实体类中,并添加到泛型集合中
* 4:将集合转化为Json数据
* 5:解析json数据 一般解析为javaBean
* 6:解析为泛型集合
* */
public String ImageResource(){
list_musicListBean_toJson = new ArrayList<>();
for (int i=0;i<imageUrl.length;i++){
dmBean = new DiscoverMusicListBean();
dmBean.setImageUrl(imageUrl[i]);
dmBean.setMusicNameBean(musicName[i]);
list_musicListBean_toJson.add(dmBean);
}
Log.e(TAG,list_musicListBean_toJson.toString());
/*
* toJson 实体类转Json数据
* fromJson Json数据转为实体类
*
* */
Gson gson = new Gson();
String strinGson = gson.toJson(list_musicListBean_toJson);
Log.e(TAG,strinGson);
return strinGson;
}
public void AnalysisJson(String sJson){
//第一种 先转为数组 数组转集合
// DiscoverMusicListBean[] dmb = new Gson().fromJson(sJson,DiscoverMusicListBean[].class);
// list_musicListBean_formJson = Arrays.asList(dmb);
//第二种:直接转泛型集合
Gson gson = new Gson();
list_musicListBean_formJson = gson.fromJson(sJson,new TypeToken<List<DiscoverMusicListBean>>(){}.getType());
// 解析为JavaBean
// DiscoverMusicListBean aa = new Gson().fromJson(sJson,DiscoverMusicListBean.class);
}
打印的东西
[DiscoverMusicList{imageUrl=2131492893, musicName='林俊杰'},
DiscoverMusicList{imageUrl=2131492898, musicName='刘德华'},
DiscoverMusicList{imageUrl=2131492899, musicName='李玉刚'},
DiscoverMusicList{imageUrl=2131492926, musicName='王菲'},
DiscoverMusicList{imageUrl=2131492927, musicName='许嵩'},
DiscoverMusicList{imageUrl=2131492928, musicName='杨钰莹'},
DiscoverMusicList{imageUrl=2131492929, musicName='张国荣'},
DiscoverMusicList{imageUrl=2131492930, musicName='张杰'},
DiscoverMusicList{imageUrl=2131492931, musicName='张靓颖'},
DiscoverMusicList{imageUrl=2131492932, musicName='周杰伦'}]
[{"musicName":"林俊杰","imageUrl":2131492893},{"musicName":"刘德华","imageUrl":2131492898},
{"musicName":"李玉刚","imageUrl":2131492899},{"musicName":"王菲","imageUrl":2131492926},
{"musicName":"许嵩","imageUrl":2131492927},{"musicName":"杨钰莹","imageUrl":2131492928},
{"musicName":"张国荣","imageUrl":2131492929},{"musicName":"张杰","imageUrl":2131492930},
{"musicName":"张靓颖","imageUrl":2131492931},{"musicName":"周杰伦","imageUrl":2131492932}]