您的位置:首页 > Web前端 > JavaScript

Gson 与 fastJson 的使用

2016-04-22 18:09 579 查看
这几天一直在写自己的小App,本来已经做好充分的准备了,可是真正开始做起来,问题接连而出,各种问题。最大的问题在于走弯路这件事,还是真走不起。太费时间,太没效率了,昨天下午六点多就开始搞笑话的一部分,主要就是从网上获取json数据然后进行解析就行,但是问题来了,如果按照常规的方式进行处理,就麻烦多了。之前就听过google的Gson,但一直没使用过。昨天晚上就学学吧,然后恶心的事情就发生了,大约从晚上八点多搞到十一点多,竟然得到的数据问null,就是不知道什么问题。昨天晚上脑袋也是混,就连博客上的Bean这个类写的我也是懵圈。

今天早晨起床一想,心里就是不甘心,然后就逃课了,上午索性没去上课。从头理了理,应该是Bean这个类可能有问题,把问题发贴吧有人推荐我是用GsonFormat这个插件,下载完后果然好用。

1、对于GsonFormat这个插件,的作用就是自动生成Bean类的,安装和使用方法

安装:studio 的 File --> Settings --> Plugins --> Browse repositories -->输入 GsonFormat 进行查找这个插件并进行安装,根据引导进行重启studio就安装完成。
使用:首先通过电脑浏览器将请求的url结果,复制下来。新建一个Bean类,将光标放进类的花括号内,点击studio的菜单栏Code --> Generate --->GsonFormat 将复制的json数据粘贴进去就可以了,这样就可以自动生成类了。





在写Json解析代码前需要添加依赖库。以前我都是直接在build.gradle 文件中直接添加的,这样做简单,但是有一个小缺点就是可能的不到最新的库文件。咱们就按照标准的形式进行添加吧。 右键项目名如果在 android类中的话就是app字符啦。选择则Open Module Settings --->Dependencies ---->选择加号--->Library dependency --->进行查找库。



按照这种方式添加查找 Gson 和 Fastjson 库 并添加。

这两个库是当前最新的:

compile 'com.google.code.gson:gson:2.6.2'
compile 'com.alibaba:fastjson:1.2.9'


2、生成的bean类 (GsonAndFastjsonBean)

package com.example.hejingzhou.gsondemo.utilise;

import java.util.List;

/**
* Created by Hejingzhou on 2016/4/22.
*/
public class GsonAndFastjsonBean {

private int error_code;//返回错误代码
private String reason;//返回说明
private ResultBean result;//把object&&{**} 类型的写成类的模式

public int getError_code() {
return error_code;
}

public void setError_code(int error_code) {
this.error_code = error_code;
}

public String getReason() {
return reason;
}

public void setReason(String reason) {
this.reason = reason;
}

public ResultBean getResult() {
return result;
}

public void setResult(ResultBean result) {
this.result = result;
}

public static class ResultBean {
/**
* content : 我拖着老婆的下巴,凝视着她的面颊:“你这张脸我怎么看都看不腻。”老婆有些害羞:“讨厌,为什么啊?”“没听过吗?肥而不腻。”
* hashId : b9b91b6cde63622a38559b4950584e04
* unixtime : 1461254031
* updatetime : 2016-04-21 23:53:51
*/

private List<DataBean> data;

public List<DataBean> getData() {
return data;
}

public void setData(List<DataBean> data) {
this.data = data;
}

public static class DataBean {
private String content;
private String hashId;
private int unixtime;
private String updatetime;

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public String getHashId() {
return hashId;
}

public void setHashId(String hashId) {
this.hashId = hashId;
}

public int getUnixtime() {
return unixtime;
}

public void setUnixtime(int unixtime) {
this.unixtime = unixtime;
}

public String getUpdatetime() {
return updatetime;
}

public void setUpdatetime(String updatetime) {
this.updatetime = updatetime;
}
}
}
}


3、创建联网取数据和解析Json的类(NetRequestData)

package com.example.hejingzhou.gsondemo.net;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.hejingzhou.gsondemo.utilise.GsonAndFastjsonBean;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
* Created by Hejingzhou on 2016/4/21.
*/
public class NetRequestData {
private String TAG = getClass().getCanonicalName();
private Thread thread;
public static String resultData;
public static String Data;

public Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0) {//用gson解析Json
Data = msg.obj.toString().replace("null", "");
Log.i(TAG, "去掉null前字符后" + Data);
Gson gson = new Gson();
GsonAndFastjsonBean gsonBean = gson.fromJson(Data, GsonAndFastjsonBean.class);
Log.i(TAG, "反序列完后" + gsonBean);
/**
*  This method deserializes the specified Json into an object of the specified class.
*  此方法将指定的 Json 反序列化为指定类的对象
* */
Log.i(TAG, "取得的错误代码" + gsonBean.getError_code());
Log.i(TAG, "取得返回结果说明" + gsonBean.getReason());
Log.i(TAG, "取得内容结果" + gsonBean.getResult());
Log.i(TAG, "笑话条数:" + gsonBean.getResult().getData().size());
for (int i = 0; i < gsonBean.getResult().getData().size(); i++) {
Log.i(TAG, gsonBean.getResult().getData().get(i).getContent());
Log.i(TAG, gsonBean.getResult().getData().get(i).getHashId());
Log.i(TAG, "" + gsonBean.getResult().getData().get(i).getUnixtime());
Log.i(TAG, gsonBean.getResult().getData().get(i).getUpdatetime());
Log.i(TAG, "************************************************");
}

} else if (msg.what == 1) {//用Jastjson 进行同样的解析
Data = msg.obj.toString().replace("null", "");
JSONObject jsonObject = JSON.parseObject(Data);
Log.i(TAG, "WWWWWWW" + jsonObject);

GsonAndFastjsonBean gsonBean = JSON.parseObject(Data, GsonAndFastjsonBean.class);
/**
*fastJson 用的Bean类都一样
* */
for (int a = 0; a < gsonBean.getResult().getData().size(); a++) {
Log.i(TAG, "HashId" + gsonBean.getResult().getData().get(a).getHashId());//获取所有哈希值
Log.i(TAG, "+++++++++++++++++++++++++++++++++++++++++++++");
}
}
}
};

public String getData(final String urlPath, Boolean flag) {
thread = new Thread(new Runnable() {
@Override
public void run() {
InputStream inputStream;
InputStreamReader inputStreamReader;
BufferedReader bufferedReader;
String readLine;
try {
URL url = new URL(urlPath);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoInput(true);
if (httpURLConnection.getResponseCode() == 200) {
inputStream = httpURLConnection.getInputStream();
if (inputStream != null) {
inputStreamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(inputStreamReader);
while ((readLine = bufferedReader.readLine()) != null) {
resultData += readLine;
}
Message message = new Message();
Message message1 = new Message();
message.what = 0;
message1.what = 1;
message.obj = resultData;
message1.obj = resultData;
handler.sendMessage(message);
handler.sendMessage(message1);
// Log.i(TAG, "获取数据流获取的数据字符串为: " + resultData);
} else Log.i(TAG, "返回数据流为空");
} else Log.i(TAG, "服务器返回数据出错,返回代码: " + httpURLConnection.getResponseCode());

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
if (flag == true) {
thread.start();
}
return resultData;
}

}


还是比较简单的,核心是与区别是:
gson :
Gson gson = new Gson();

GsonAndFastjsonBean gsonBean = gson.fromJson(Data, GsonAndFastjsonBean.class);

fastjson:
import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;

GsonAndFastjsonBean gsonBean = JSON.parseObject(Data, GsonAndFastjsonBean.class);

有人说fastjson效率高,我这个外行人只解析小的数据,是没有差别的,那个顺眼就用哪个。

4、MainActivity 打开链接,启动方法线程

netRequestData = new NetRequestData();
resultData = netRequestData.getData("http://japi.juhe.cn/joke/content/list.from?key=11479a717dca830000dc0edd3d1ba250&page=2&pagesize=20&sort=asc&time=1418700237", true);
/**
* 请求参数说明:
名称	类型	必填	说明
sort	string	是	类型,desc:指定时间之前发布的,asc:指定时间之后发布的
page	int	否	当前页数,默认1
pagesize	int	否	每次返回条数,默认1,最大20
time	string	是	时间戳(10位),如:1418816972
key	string	是	您申请的key
* */


看一下log:



源码; http://download.csdn.net/detail/csdnhejingzhou/9499644
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: