从网上看了一下如何提取json格式的文件内容,很多文章没有办法直接运行,于是我进行了一个整合,按照我的方法一定能写出来的。
一、创建MapBean类
首先我自己创建了一个MapBean类,类中主要有类型viewType,标题caption和装载多个子项的列表childList,childList需要存放多个MapBean类型的实例。这些变量是我需要在json文件当中存储的。
public class MapBean implements Serializable {
public static final int TYPE_PARENT=0;//父类
public static final int TYPE_CHILD=1;//子类
private int viewType; //类型
private String caption; //标题
private List<MapBean> childList;//定义一个装载多个子类的列表
public MapBean(String caption,int viewType){//表示获得的消息类型
this.caption=caption;
this.viewType=viewType;
}
public int getViewType(){
return viewType;
}
public String getCaption(){
return caption;
}
//折叠展开列表
public void setChildList(List<MapBean> childList){
this.childList=childList;
}
public List<MapBean> getChildList(){
return childList;
}
}
二、创建json文件
我们需要创建与MapBean相对应的json文件,我们在main下面新增一个assert目录,然后在里面创建一个MapBean.json文件,内容格式如下,可以看到childList当中又存放了多个实例:
[
{
"caption": "创建地图",
"viewType": 0,
"childList": [
{
"caption": "创建地图",
"viewType": 1,
"childList": null
},
{
"caption": "纯地图",
"viewType": 1,
"childList": null
}
]
},
{
"caption": "地图计算工具",
"viewType": 0,
"childList": [
{
"caption": "地图计算",
"viewType": 1,
"childList": null
},
{
"caption": "经纬度转屏幕像素",
"viewType": 1,
"childList": null
}
]
}
]
三、读取数据
我们需要在主活动中读取数据,此时我在MainActivity活动类初始化的时候写一个initMap()方法:
public class MainActivity extends AppCompatActivity {
private List<MapBean> mapBeanList;//定义全局列表
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initMaps();
}
initMap()方法定义如下:
private void initMaps() {
// 解析Json数据
StringBuilder newstringBuilder = new StringBuilder();
InputStream inputStream = null;
try {
inputStream = getResources().getAssets().open("MapBean.json");
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(isr);
String jsonLine;
while ((jsonLine = reader.readLine()) != null) {
newstringBuilder.append(jsonLine);
}
reader.close();
isr.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
String str = newstringBuilder .toString();
Gson gson = new Gson();
Type MapBeanListType = new TypeToken<ArrayList<MapBean>>(){}.getType();
mapBeanList=gson.fromJson(str, MapBeanListType);
}
我们首先将字符串类型读取出来,采用:
String str = newstringBuilder .toString();
然后我们采用Gson进行反序列化,对于List,反序列化时必须提供它的Type,通过Gson提供的TypeToken.getType()方法可以定义当前List的Type:
Gson gson = new Gson();
Type MapBeanListType = new TypeToken<ArrayList<MapBean>>(){}.getType();
mapBeanList=gson.fromJson(str, MapBeanListType);
最终可以看到调试的时候的结果如下所示,就直接将json中的变量实例保存到mapBeanList当中了,然后后续就可以进行运用了。