1. 程式人生 > >Android獲取assets資料夾下的json資料,並Gson解析!

Android獲取assets資料夾下的json資料,並Gson解析!

Json 資料如下

{
"code": 200,
"msg": "ok",
"news": [
        {
"title": "空降美國的孩子",
"content": "在壓力和青春期的情緒波動之中,他們經歷著不一樣的高中歲月。",
"imageUrl": "http://img1.gtimg.com/ninja/2/2018/02/ninja151798030871223.jpg"
},
{
"title": "中國人的一天",
"content": "男子獨守羌王府,村莊成景區,靠景點旅遊收入,養活全村孤寡老人",
"imageUrl": "http://img1.gtimg.com/news/pics/hv1/119/227/2274/147924854.jpg"
}, { "title": "霍金的三次中國之行", "content": "霍金與中國的緣分不淺,他曾3次來華。", "imageUrl": "http://img1.gtimg.com/ninja/1/2018/03/ninja152102147694339.jpg" }, { "title": "一位英國人留給貴州苗族的遺產", "content": "從原始苗寨到 “ 文化聖地 ” ,石門坎所經歷的一切,全因一位外國人的到來和時代鉅變。", "imageUrl": "http://img1.gtimg.com/ninja/1/2018/03/ninja152161950735699.jpg" }, { "title": "中國女攝影師鏡頭下的敘利亞"
, "content": "人間若有天堂,大馬士革必在其中。", "imageUrl": "http://img1.gtimg.com/ninja/1/2018/04/ninja152414932060578.jpg" }, { "title": "震後十年,田埂上那姑娘從未跑遠", "content": "後來我去了大學,她留在了地震博物館", "imageUrl": "http://img1.gtimg.com/news/pics/hv1/174/161/2274/147908079.jpg" } ] }

解析 

news.json是檔名字,另外需要兩個實體類,根據資料格式自行建立。

StringBuilder newstringBuilder = new 
StringBuilder(); InputStream inputStream = null; try { inputStream = getResources().getAssets().open("news.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 result = newstringBuilder .toString(); Log.d("json",result); Gson gson = new Gson(); Common common = gson.fromJson(result, Common.class); newlist=common.getNews();