我假设你不打算以任何方式处理纬度/经度对,因为你再没提到它,你的“行”应该是这样的:
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