第一种使用JSONObject解析JSON数据,这是Android中最基本的数据解析方式
fromJson("{'status':200," +
"'message':'ok'," +
"'people':{" +
"'username':'LiLy'," +
"'phone':'13189720413'," +
"'headerImg':'https://img0.baidu.com/it/u=1521420901,2700109129&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=313'}}");
private void fromJson(String s) {
Me me=new Me();
JSONObject jsonObject= null;
try {
jsonObject = new JSONObject(s);
int status=jsonObject.optInt("status");
me.setStatus(status);
String message=jsonObject.optString("message");
me.setMessage(message);
JSONObject uesrJson=jsonObject.optJSONObject("people");
String username=uesrJson.optString("username");
String phone=uesrJson.optString("phone");
String headerImg=uesrJson.optString("headerImg");
me.setPeople(new People(username,phone,headerImg));
Log.d("","Json======"+status+"\t"+message+"\t"+username+"\t"+phone+"\t"+headerImg);
} catch (JSONException e) {
e.printStackTrace();
}
}
第二种方式通过GSON去解析JSON数据
同样的数据格式
objectFromJson("{'status':200," +
"'message':'ok'," +
"'people':{" +
"'username':'LiLy'," +
"'phone':'13189720413'," +
"'headerImg':'https://img0.baidu.com/it/u=1521420901,2700109129&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=313'}}");
private void objectFromJson(String s) {
Gson gson=new Gson();
Me me = gson.fromJson(s, Me.class);
Log.d("","me======="+me.toString());
}
GSON的数据解析看起来代码量相对小一点,但所创建的类也是必须的
第一个支持的类,此类为自定义名字,为了方便随意起的,但在项目中要正规取名,见名知意文章来源:https://www.toymoban.com/news/detail-514638.html
class Me{
int status;
String message;
People people;
public Me(){}
public Me(int status, String message, People people) {
this.status = status;
this.message = message;
this.people = people;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public People getPeople() {
return people;
}
public void setPeople(People people) {
this.people = people;
}
@Override
public String toString() {
return "Me{" +
"status=" + status +
", message='" + message + '\'' +
", people=" + people +
'}';
}
}
第二个支持的类文章来源地址https://www.toymoban.com/news/detail-514638.html
class People {
private String username;
private String phone;
private String headerImg;
public People(String username, String phone, String headerImg) {
this.username = username;
this.phone = phone;
this.headerImg = headerImg;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getHeaderImg() {
return headerImg;
}
public void setHeaderImg(String headerImg) {
this.headerImg = headerImg;
}
@Override
public String toString() {
return "People{" +
"username='" + username + '\'' +
", phone='" + phone + '\'' +
", headerImg='" + headerImg + '\'' +
'}';
}
到了这里,关于Android 解析JSON数据的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!