之前写了一篇博文是获取服务器数据并解析显示到listview上,上次使用的解析是通过jsonarray和jsonobject完成,解析json的数据还是可以,但是发现解析复杂点的数据真的很麻烦,然后查了一下Gson的解析方式写了一个demo,发现省事了许多.上代码:
效果图: 项目结构图:
1.json数据:
[
{
"title": "网络部",
"date": "2017",
"counnt": "16",
"pic":"http://cdn-img.easyicon.net/png/11184/1118405.gif"
},
{
"title": "运营部",
"date": "2017",
"counnt": "6",
"pic":"http://cdn-img.easyicon.net/png/11184/1118405.gif"
},
{
"title": "金融部",
"date": "2017",
"counnt": "20",
"pic":"http://cdn-img.easyicon.net/png/11184/1118405.gif"
},
{
"title": "其他",
"date": "2017",
"counnt": "8",
"pic":"http://cdn-img.easyicon.net/png/11184/1118405.gif"
}
]
Gson库我直接在Androidstudio中添加,其他两个库我是复制到libs中
okhttp下载地址:http://download.csdn.net/detail/qq_26650589/9811409
Picasso下载:http://download.csdn.net/detail/qq_26650589/9695886
如何引用架包我就不详细写了,如果不知如何添加请看博文地址:http://blog.csdn.net/qq_26650589/article/details/73159658
3、activity_main.xml布局
一个简单的listview控件
创建布局listview_item,,用来显示每个listview的item内容,布局中代码:
public class user {
private String title;//部门
private String date;//时间
private String counnt;//人数
private String pic;//图片
public user(String title, String date, String counnt,String pic) {
this.title = title;
this.date = date;
this.counnt = counnt;
this.pic=pic;
}
public String getTitle() {
return title;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCounnt() {
return counnt;
}
public void setCounnt(String counnt) {
this.counnt = counnt;
}
}
public class MainActivity extends AppCompatActivity {
public String date;
public ListView lv;
public ArrayList listuser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv= (ListView) findViewById(R.id.lv);
init();
//listview点击事件
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this,""+listuser.get(position).getTitle(),Toast.LENGTH_LONG).show();
}
});
}
//获取json数据部分
private void init() {
new Thread(new Runnable() {
public void run() {
OkHttpClient okHttpClient = new OkHttpClient();
//服务器返回的地址
Request request = new Request.Builder()
.url("http://192.168.1.154/user.json").build();
try {
Response response = okHttpClient.newCall(request).execute();
//获取到数据
date = response.body().string();
//在线程中没有办法实现主线程操作
Message message = new Message();
message.what = 1;
han.sendMessage(message);
//把数据传入解析josn数据方法
Gsonjx(date);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public android.os.Handler han = new android.os.Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
Toast.makeText(MainActivity.this,""+date,Toast.LENGTH_LONG).show();
break;
case 2:
lv.setAdapter(new useradapter(MainActivity.this, listuser));//调用listview适配器
break;
}
}
};
private void Gsonjx(String date) { //gson解析部分
JsonParser parser = new JsonParser();
JsonArray jsonArray = parser.parse(date).getAsJsonArray();
Gson gson = new Gson();
listuser = new ArrayList<>();
for (JsonElement user : jsonArray) {
user userBean = gson.fromJson(user, user.class);
listuser.add(userBean);
}
Message message = new Message();
message.what = 2;
han.sendMessage(message);
}
}
public class useradapter extends BaseAdapter {
public Context con;
public List list;
public LayoutInflater inflater;
public useradapter(Context context, List user){
this.con=context;
this.list=user;
inflater=LayoutInflater.from(con);
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view= inflater.inflate(R.layout.listview_item,null);
TextView tv1= (TextView) view.findViewById(R.id.tv1);
TextView tv2= (TextView) view.findViewById(R.id.tv2);
TextView tv3= (TextView) view.findViewById(R.id.tv3);
ImageView img= (ImageView) view.findViewById(R.id.img);
tv1.setText("部门:"+list.get(position).getTitle());
tv2.setText("时间:"+list.get(position).getDate());
tv3.setText("人数:"+list.get(position).getCounnt());
//判断获取的json中图片是否为空
if (TextUtils.isEmpty(list.get(position).getPic().toString())){
Picasso
.with(con)
.cancelRequest(img);
img.setImageDrawable(con.getResources().getDrawable(R.mipmap.ic_launcher));//当图片为空时显示原始机器人图
}else {
//图片加载
Picasso
.with(con)
.load(list.get(position).getPic().toString())
.placeholder(R.mipmap.ic_launcher)//图片加载中时显示原始机器人图
.into(img);
}
return view;
}
}
在AndroidManifest.xml中添加访问网络权限
(1)、如果你发现运行结果的信息显示为null,请检查实体类里的变量名称是否和json数据的内容相同
(2)、如果你发现报错的信息是: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 20 column 10 path $[2].counnt,请使用json工具检查json数据是否正确。
二、使用Gson解析稍微复杂json数据
json数据:
{
"result": "true",
"counnts": 4,
"user": [
{
"title": "网络部",
"date": "2017",
"counnt": "16",
"pic": "http://cdn-img.easyicon.net/png/11184/1118405.gif"
},
{
"title": "运营部",
"date": "2017",
"counnt": "6",
"pic": "http://cdn-img.easyicon.net/png/11184/1118405.gif"
},
{
"title": "金融部",
"date": "2017",
"counnt": "20",
"pic": "http://cdn-img.easyicon.net/png/11184/1118405.gif"
},
{
"title": "其他",
"date": "2017",
"counnt": "8",
"pic": "http://cdn-img.easyicon.net/png/11184/1118405.gif"
}
]
}
1、创建实体类
public class UserBean {
//变量名需要与json字段的名称一致
private String result;
private int counnts;
private List user;
public class user{
private String title;
private String date;
private String counnt;
private String pic;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCounnt() {
return counnt;
}
public void setCounnt(String counnt) {
this.counnt = counnt;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public int getCounnts() {
return counnts;
}
public void setCounnts(int counnts) {
this.counnts = counnts;
}
public List getUser() {
return user;
}
public void setUser(List user) {
this.user = user;
}
}
private void Gsonjx(String date) {
UserBean resultBean = new Gson().fromJson(date,UserBean.class);
List listuser = resultBean.getUser();
Message message = new Message();
message.what = 2;
han.sendMessage(message);
}
一些listview适配代码就不贴了和上面一样就改了一下Gsonjx()方法里的代码
解析更多的json样式地址:https://github.com/IamXiaRui/Android_5.0_ViewDemo/tree/master/GsonArrayDemo