You don't have to set a Setters / Constructors , you should only use annotations.
For example if your server response is as follows:
{
"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
}]
}
You have to create a Device class and a Devices Response class as follows:
Device Class:
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;
}
}
Devices Response Class:
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 - I only used contractors for convenience.
If you have to create a POST message you should create a DeviceRequest as well that reflects you JSON structure passed in the body of the request.
Notice that the name inside @SerializedName("name of a json field") should be a real JSON key.