196.m1-解析服务器请求的json数据

来源:互联网 发布:sql正则 编辑:程序博客网 时间:2024/05/21 22:54

解析json的原则,把里面的内容的条目封装成一个类,通过在bean中封装每一个变量,见到大括号 就用JsonObject ,见到中括号就是JsonArray,再使用list来封装每一个类。

json数据举例如下

{    "picture": [        "image/home01.jpg",        "image/home02.jpg",        "image/home03.jpg",        "image/home04.jpg",        "image/home05.jpg",        "image/home06.jpg",        "image/home07.jpg",        "image/home08.jpg"    ],    "list": [        {            "id": 1525490,            "name": "有缘网",            "packageName": "com.youyuan.yyhl",            "iconUrl": "app/com.youyuan.yyhl/icon.jpg",            "stars": 4,            "size": 3876203,            "downloadUrl": "app/com.youyuan.yyhl/com.youyuan.yyhl.apk",            "des": "产品介绍:有缘是时下最受大众单身男女亲睐的婚恋交友软件。有缘网专注于通过轻松、"        },        {            "id": 1599700,            "name": "酷狗音乐",            "packageName": "com.kugou.android",            "iconUrl": "app/com.kugou.android/icon.jpg",            "stars": 4,            "size": 8790060,            "downloadUrl": "app/com.kugou.android/com.kugou.android.apk",            "des": "全新改版震撼发布!让您赏心悦目、随心所欲、乐在其中、知音识趣......还有多项"        },        {            "id": 1633797,            "name": "唯品会",            "packageName": "com.achievo.vipshop",            "iconUrl": "app/com.achievo.vipshop/icon.jpg",            "stars": 4,            "size": 5142608,            "downloadUrl": "app/com.achievo.vipshop/com.achievo.vipshop.apk",            "des": "【网购神器】唯品会,一家专门做特卖的网站,专业买手把脉潮流热点,轻松打造女神范"        },
数据的解析,首先封装一个bean对象AppInfo来存放条目中的数据

//解析json数据private List<AppInfo> parseJson(String json) {List<AppInfo> appInfos = new ArrayList<AppInfo>();try {JSONObject jsonObject = new JSONObject(json);//获取到中括号的内容JSONArray jsonArray = jsonObject.getJSONArray("list");//遍历list数组,list数组里面又是由大括号构成for(int i = 0; i < jsonArray.length(); i++){JSONObject jsonObj = jsonArray.getJSONObject(i);long id = jsonObj.getLong("id");String name = jsonObj.getString("name");String packageName = jsonObj.getString("packageName");String iconUrl = jsonObj.getString("iconUrl");float stars = Float.parseFloat(jsonObj.getString("stars"));long size = jsonObj.getLong("size");String downloadUrl = jsonObj.getString("downloadUrl");String des = jsonObj.getString("des");//构造函数,创建一个appInfoAppInfo appInfo = new AppInfo(id, name, packageName, iconUrl,stars, size, downloadUrl, des);//往集合中添加对象appInfos.add(appInfo);}return appInfos;} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();return null;}

代码如下

AppInfo.java

package com.ldw.market.domain;public class AppInfo {         private long id;private String name;private String packageName;private String iconUrl;private float stars;private long size;private String downloadUrl;private String des;public long getId() {return id;}public void setId(long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPackageName() {return packageName;}public void setPackageName(String packageName) {this.packageName = packageName;}public String getIconUrl() {return iconUrl;}public void setIconUrl(String iconUrl) {this.iconUrl = iconUrl;}public float getStars() {return stars;}public void setStars(float stars) {this.stars = stars;}public long getSize() {return size;}public void setSize(long size) {this.size = size;}public String getDownloadUrl() {return downloadUrl;}public void setDownloadUrl(String downloadUrl) {this.downloadUrl = downloadUrl;}public String getDes() {return des;}public void setDes(String des) {this.des = des;}public AppInfo() {super();}public AppInfo(long id, String name, String packageName, String iconUrl,float stars, long size, String downloadUrl, String des) {super();this.id = id;this.name = name;this.packageName = packageName;this.iconUrl = iconUrl;this.stars = stars;this.size = size;this.downloadUrl = downloadUrl;this.des = des;}@Overridepublic String toString() {return "AppInfo [id=" + id + ", name=" + name + ", packageName="+ packageName + ", iconUrl=" + iconUrl + ", stars=" + stars+ ", size=" + size + ", downloadUrl=" + downloadUrl + ", des="+ des + "]";}}

解析部分的代码HomeProtacal.java

package com.ldw.market.protocol;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.StringWriter;import java.util.ArrayList;import java.util.List;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import com.ldw.market.domain.AppInfo;import com.ldw.market.http.HttpHelper;import com.ldw.market.http.HttpHelper.HttpResult;import com.ldw.market.utils.FileUtils;import com.lidroid.xutils.HttpUtils;import com.lidroid.xutils.exception.HttpException;import com.lidroid.xutils.http.ResponseStream;import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;import com.lidroid.xutils.util.IOUtils;public class HomeProtocal {//请求服务器数据,参数index,可以分批加载public List<AppInfo> load(int index){//从本地请求数据String json = loadLocal(index);//返回的数据是jsonif(json == null){json = loadServer(index);//保存到本地if(json != null){saveLocal(json, index);}}else{System.out.println("使用了本地缓存");}//json不为空,就解析jsonif(json != null){return parseJson(json);}else{return null;}}//解析json数据private List<AppInfo> parseJson(String json) {List<AppInfo> appInfos = new ArrayList<AppInfo>();try {JSONObject jsonObject = new JSONObject(json);//获取到中括号的内容JSONArray jsonArray = jsonObject.getJSONArray("list");//遍历list数组,list数组里面又是由大括号构成for(int i = 0; i < jsonArray.length(); i++){JSONObject jsonObj = jsonArray.getJSONObject(i);long id = jsonObj.getLong("id");String name = jsonObj.getString("name");String packageName = jsonObj.getString("packageName");String iconUrl = jsonObj.getString("iconUrl");float stars = Float.parseFloat(jsonObj.getString("stars"));long size = jsonObj.getLong("size");String downloadUrl = jsonObj.getString("downloadUrl");String des = jsonObj.getString("des");//构造函数,创建一个appInfoAppInfo appInfo = new AppInfo(id, name, packageName, iconUrl,stars, size, downloadUrl, des);//往集合中添加对象appInfos.add(appInfo);}return appInfos;} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();return null;}}//将json保存在本地:方法1把整个json文件写到一个本地文件中,方法2吧每条数据都摘出来保存在数据库中private void saveLocal(String json, int index) {//创建一个bufferBufferedWriter bw = null;try {File dir=FileUtils.getCacheDir();//创建一个文件File file = new File(dir, "home_" + index); // /mnt/sdcard/market/cache/home_0FileWriter fw = new FileWriter(file); bw = new BufferedWriter(fw);//在第一行写一个过期时间 bw.write(System.currentTimeMillis() + 1000 * 100 + "");bw.newLine();// 换行bw.write(json);// 把整个json文件保存起来bw.flush();bw.close();} catch (Exception e) {e.printStackTrace();}finally{IOUtils.closeQuietly(bw);}}//从服务器请求json数据private String loadServer(int index) {//请求地址http://127.0.0.1:8090/home?index=1HttpResult httpResult = HttpHelper.get(HttpHelper.URL +"home"+ "?index=" + index); //得到结果String json = httpResult.getString();//System.out.println(json);return json;}//加载本地保存的数据private String loadLocal(int index) {// 如果发现时间过期了,就不用本地的缓存File dir=FileUtils.getCacheDir();// 获取缓存所在的文件夹//得到缓存文件File file = new File(dir, "home_" + index); try {FileReader fr=new FileReader(file);BufferedReader br=new BufferedReader(fr);//获取过期时间long outOfDate = Long.parseLong(br.readLine());//判断是否过期,if(System.currentTimeMillis()>outOfDate){return null;}else{String str=null;StringWriter sw=new StringWriter();while((str=br.readLine())!=null){sw.write(str);}return sw.toString();}} catch (Exception e) {e.printStackTrace();return null;}}}

HomeFragment.java测试

package com.ldw.market.fragment;import java.util.List;import android.os.Bundle;import android.view.View;import android.widget.TextView;import com.ldw.market.domain.AppInfo;import com.ldw.market.protocol.HomeProtocal;/* * Home页面,主体的加载的几个页面和服务器请求数据都是在BaseFragment中去实现 */public class HomeFragment extends BaseFragment {// 当Fragment挂载的activity创建的时候调用@Overridepublic void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);show();}public View createSuccessView() {TextView tv = new TextView(getActivity());tv.setText("加载成功了....");tv.setTextSize(30);return tv;}@Overridepublic LoadResult load() {HomeProtocal protocol = new HomeProtocal();List<AppInfo> appInfos = protocol.load(0);for(AppInfo appInfo:appInfos){System.out.println(appInfo);}return LoadResult.success;}}