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
}]
}
あなたは次のようにデバイスクラスとデバイスレスポンスクラスを作成する必要があります。
デバイスクラス:
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メッセージを作成する必要がある場合は、要求の本体で渡されたJSON構造を反映するDeviceRequestも作成する必要があります。
@SerializedName内の名前( "jsonフィールドの名前")が実際のJSONキーであることに注意してください。
回答ありがとうございますが、フィールドを変更する必要がある場合、どうすればよいですか?私の場合は、データを正確に「クリア」することはできません(一部のフィールドにはプレーンテキストの代わりにhtmlが含まれています)。もちろん、私はゲッターでそれらを修正することができますが、私はオブジェクト(オブジェクトの作成の瞬間)で直接修正したいと思います。 – Mikhail
@Mikhail、サンプルレスポンスを共有できますか?あなたのレスポンスはJSON形式ですか? –
@Mikhail、Gsonはv2.3(https://github.com/google/gson/issues/232)からのセッターのみで動作します。現在、カスタムバージョン2.1で作業しています。 https://search.maven.org/#search%7Cga%7C1%7Ccom.squareup.retrofit2 セッターで作業したい場合は、ジャクソンまたは他のコンバータを使用する必要があります。私は個人的には過去にジャクソンと仕事をしていました。 –