您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用com.google.gson类创建json对象

如何使用com.google.gson类创建json对象

这样,您可以为响应编写POJO / Model类

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

@SerializedName("role")
@Expose
private String role;
@SerializedName("operationId")
@Expose
private String operationId;
@SerializedName("parameters")
@Expose
private Parameters parameters;

public String getRole() {
return role;
}

public void setRole(String role) {
this.role = role;
}

public String getOperationId() {
return operationId;
}

public void setOperationId(String operationId) {
this.operationId = operationId;
}

public Parameters getParameters() {
return parameters;
}

public void setParameters(Parameters parameters) {
this.parameters = parameters;
}

}
package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class HomePlace {

@SerializedName("address")
@Expose
private String address;
@SerializedName("lat")
@Expose
private String lat;
@SerializedName("lng")
@Expose
private String lng;

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getLat() {
return lat;
}

public void setLat(String lat) {
this.lat = lat;
}

public String getLng() {
return lng;
}

public void setLng(String lng) {
this.lng = lng;
}

}
package com.example;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Parameters {

@SerializedName("tcId")
@Expose
private String tcId;
@SerializedName("otpVerification")
@Expose
private String otpVerification;
@SerializedName("password")
@Expose
private String password;
@SerializedName("homePlace")
@Expose
private List<HomePlace> homePlace = null;

public String getTcId() {
return tcId;
}

public void setTcId(String tcId) {
this.tcId = tcId;
}

public String getOtpVerification() {
return otpVerification;
}

public void setOtpVerification(String otpVerification) {
this.otpVerification = otpVerification;
}

public String getpassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public List<HomePlace> getHomePlace() {
return homePlace;
}

public void setHomePlace(List<HomePlace> homePlace) {
this.homePlace = homePlace;
}

}

在将json解析为使用Gson的自定义模型之后

Gson gson = new GsonBuilder().create();
Example yourModelClass = gson.fromJson(yourJsonResponse, Example .class);
Go 2022/1/1 18:25:47 有298人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶