【发布时间】:2019-02-20 18:09:59
【问题描述】:
{ “状态”:是的, "message": "欢迎 jaymin", “数据”: { “身份证”:1, “名称”:“杰明”, “电子邮件”:“jaymin@gmail.com”, “手机”:“123456” } }
【问题讨论】:
-
我们真的需要Retrofit 2来解析Json吗?
-
@Toaster : 我们可以使用
{ “状态”:是的, "message": "欢迎 jaymin", “数据”: { “身份证”:1, “名称”:“杰明”, “电子邮件”:“jaymin@gmail.com”, “手机”:“123456” } }
【问题讨论】:
您可以添加 GsonFactory 或 JacksonFactory 来创建改造服务 并且可以使用这个链接http://www.jsonschema2pojo.org/ 创建一个 pojo 类,您可以通过该类解析数据。我已将您的 JSON 转换为 Gson 格式的 java 类,您可以在 android 中使用它来解析数据。
-----------------------------------com.example.Data.java-----------------------
------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Data {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("email")
@Expose
private String email;
@SerializedName("mobile")
@Expose
private String mobile;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
}
-----------------------------------com.example.FollowersResponse.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class FollowersResponse {
@SerializedName("status")
@Expose
private Boolean status;
@SerializedName("message")
@Expose
private String message;
@SerializedName("data")
@Expose
private Data data;
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
【讨论】:
要将字符串转换为 JSONObject,请执行以下操作
String jsonString = '{ "status": true, "message": "Welcome jaymin", "data": { "id": 1, "name": "jaymin", "email": "jaymin@gmail.com", "mobile": "123456" } }'
JSONObject jsonObj = new JSONObject(jsonString)
然后你可以像这样从 JSONObject 中检索值
String message = jsonObj.get("message") //Message = "Welcome jaymin"
【讨论】: