前言
今天,我们用一个实际的例子来介绍现今主流的数据交换格式JSON!
Json实例
{"code":"0","msg":"success","data":[{"userId":"1","userPassword":"123","userPhone":"12345678910"}]}
java bean类
1.userMessage类
用来描述用户登录状态的类
实例:
package com.example.test;
import java.util.ArrayList;
import java.util.List;
public class UserMessage {
private Stringcode;
private Stringmsg;
private Listdata;
public UserMessage(){
this.code ="";
this.msg ="";
this.data =new ArrayList();
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List getData() {
return data;
}
public void setData(List data) {
this.data = data;
}
public void addData(Object data){
this.data.add(data);
}
}
2.user类
描述:用来描述用户个人信息的类
实例:
package com.example.test;
public class User {
private StringuserId;
private StringuserPassword;
private StringuserPhone;
public User(){
}
public String getUserId() {
return userId;
}
public String getUserPhone() {
return userPhone;
}
public String getUserPassword() {
return userPassword;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
}
Gson依赖(Android Studio开发工具)
在build.gradle中添加 implementation'com.google.code.gson:gson:2.8.5'
Json字符串转对象
这里使用的是Okhttp网络请求:
String JsonData = response.body().string();
首先获得json字符串转换成UserMessage 对象,这里可以用来判断用户登录情况
Gson gson =new Gson();
UserMessage userMessage=gson.fromJson(JsonData,UserMessage.class);
可以看到,利用GSON方法进行解析,关键在于根据json数据里面的结构写出一个对应的javaBean,而解析过程非常简单:
JavaBean对象 = gson.fromJson(son,javaBean类类名.class);
但是userMessage.getData()是List
List list=userMessage.getData(); //使用
String Json=gson.toJson(list.get(0));
User user=gson.fromJson(Json,User.class);
userId=user.getUserId();
userPhone=user.getUserPhone();
最后成功将List