如何在Retrofit 2中解析json以下?

时间:2018-09-16 18:30:34

标签: android json retrofit

{     “状态”:是,     “ message”:“ Welcome Jaymin”,     “数据”:{         “ id”:1         “ name”:“ jaymin”,         “电子邮件”:“ jaymin@gmail.com”,         “ mobile”:“ 123456”     } }

2 个答案:

答案 0 :(得分:1)

您可以添加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;
}

}

答案 1 :(得分:0)

要将字符串插入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"