我使用Retrofit库来调用请求,使用GsonСonverter转换为类对象。但API JSON响应不“清楚”,我需要手动更正某些字段(例如,将html转换为可读文本)。但转换过程中不会引起设置器。
是否可以在创建对象集字段值时仅通过其setter?
答案 0 :(得分:0)
您不必设置Setters / Constructors,只应使用注释。
例如,如果您的服务器响应如下:
{
"count": 12,
"devices": [{
"adb_url": null,
"owner": null,
"ready": true,
"serial": "XXXXXX",
"model": "GT-N7100",
"present": true
}, {
"adb_url": null,
"owner": null,
"ready": true,
"serial": "XXXXXX",
"model": "GT-I9500",
"present": true
}]
}
您必须按如下方式创建Device类和Devices Response类:
设备类:
import com.google.gson.annotations.SerializedName;
public class Device {
@SerializedName("adb_url")
String adbUrl;
@SerializedName("owner")
String owner;
@SerializedName("ready")
Boolean isReady;
@SerializedName("serial")
String serial;
@SerializedName("model")
String model;
@SerializedName("present")
Boolean present;
public Device(String adbUrl, String owner, Boolean isReady, String serial, String model, Boolean present) {
this.adbUrl = adbUrl;
this.owner = owner;
this.isReady = isReady;
this.serial = serial;
this.model = model;
this.present = present;
}
}
设备响应类:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
/**
* Created by avilevinshtein on 01/01/2017.
*/
public class DeviceResponse {
@SerializedName("count")
int deviceSize;
@SerializedName("devices")
List<Device> deviceList;
public DeviceResponse() {
deviceSize = 0;
deviceList = new ArrayList<Device>();
}
public DeviceResponse(List<Device> deviceList) {
this.deviceList = deviceList;
deviceSize = deviceList.size();
}
public DeviceResponse(int deviceSize, List<Device> deviceList) {
this.deviceSize = deviceSize;
this.deviceList = deviceList;
}
public static DeviceResponse parseJSON(String response) {
Gson gson = new GsonBuilder().create();
DeviceResponse deviceResponse = gson.fromJson(response, DeviceResponse.class);
return deviceResponse;
}
}
P.S - 我只是为了方便而使用承包商。
如果你必须创建一个POST消息,你也应该创建一个DeviceRequest,它反映了你在请求正文中传递的JSON结构。
请注意,@ SerializedName中的名称(“json字段的名称”)应该是真正的JSON密钥。