我假設你不打算以任何方式處理緯度/經度對,因爲你再沒提到它,你的「行」應該是這樣的:
final class Location {
final int ratingBest = Integer.valueOf(0);
final int reviewCount = Integer.valueOf(0);
@JsonAdapter(PackedCoordinateTypeAdapter.class)
final String coordinate = null;
}
查看將特定類型適配器綁定到該字段的@JsonAdapter
註釋。類型適配器可能看起來像這樣:
final class PackedCoordinateTypeAdapter
extends TypeAdapter<String> {
private static final String DELIMITER = " ";
private static final String LATITUDE = "latitude";
private static final String LONGITUDE = "longitude";
private static final Pattern delimiterPattern = compile(DELIMITER);
// Keep private stuff private as much possible, Gson can access it
private PackedCoordinateTypeAdapter() {
}
@Override
@SuppressWarnings("resource")
public void write(final JsonWriter out, final String packedLatitudeLongitude)
throws IOException {
final String[] split = decode(packedLatitudeLongitude);
out.beginObject();
out.name(LATITUDE);
out.value(split[0]);
out.name(LONGITUDE);
out.value(split[1]);
out.endObject();
}
@Override
public String read(final JsonReader in)
throws IOException {
String latitude = null;
String longitude = null;
in.beginObject();
while (in.hasNext()) {
final String name = in.nextName();
switch (name) {
case LATITUDE:
latitude = in.nextString();
break;
case LONGITUDE:
longitude = in.nextString();
break;
default:
throw new MalformedJsonException("Unexpected: " + name);
}
}
in.endObject();
return encode(latitude, longitude);
}
private static String encode(final String latitude, final String longitude)
throws MalformedJsonException {
if (latitude == null) {
throw new MalformedJsonException("latitude not set");
}
if (longitude == null) {
throw new MalformedJsonException("longitude not set");
}
return latitude + DELIMITER + longitude;
}
private static String[] decode(final String packedLatitudeLongitude)
throws IllegalArgumentException {
final String[] split = delimiterPattern.split(packedLatitudeLongitude);
if (split.length != 2) {
throw new IllegalArgumentException("Cannot parse: " + packedLatitudeLongitude);
}
return split;
}
}
演示:
final Location response = gson.fromJson("{\"ratingBest\":10,\"reviewCount\":1,\"coordinate\":{\"latitude\":\"-7.2768\",\"longitude\":\"112.7927\"}}", Location.class);
System.out.println(response.coordinate);
System.out.println(gson.toJson(response));
輸出:
-7.2768 112.7927
{ 「ratingBest」:10 「reviewCount」:1, 「coordinate」:{「latitude」:「 - 7.2768」,「longitude」:「112.7927」}}
你好嗎?爲了達到這個目的?你在哪裏與Gson保存模型? –
尚未實施。但對於正常的響應,我在Android中使用ORMLite helper,並且只需使用來自API的Json響應作爲參數調用'create()'方法即可。我希望一個字段'coordinate'保存爲'String',因爲Gson會自動將每個響應轉換爲特定類型。 – fanjavaid