我的API响应中有一个字段嵌套JSON:
"ratingBest": 10,
"reviewCount": 1,
"coordinate": {
"latitude": "-7.2768",
"longitude": "112.7927"
},
...
我使用ORMLite将上述数据保存到Android本地数据库,但我希望只有一个字段coordinate
为String
。导致Gson自动转换为特定类型。
我已经尝试将类字段类型用作String。但仍然没有工作
有什么解决方法吗?
谢谢
答案 0 :(得分:2)
我假设你不会以任何方式处理纬度/经度对,因为你没有提及它,你的"行"应该是这样的:
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
{&#34; ratingBest&#34;:10,&#34; reviewCount&#34;:1,&#34;坐标&#34; {&#34;纬度&#34;:&#34; -7.2768&# 34;,&#34;经度&#34;:&#34; 112.7927&#34;}}
答案 1 :(得分:0)
试试这个。
http://127.0.0.1
现在存储b
答案 2 :(得分:0)
您可以通过以下方式执行此操作:
value="{{ old('element_name_here') }}"
希望它会对你有所帮助。