我遇到问题,App Engine将Long / long值作为“String”返回。以下是返回的JSON文件的一部分:
"stringObject" : "This is a string.",
"integerPrimitive" : -3,
"intergerObject" : 3333,
"longPrimitive" : "1234567890123456789",
"longObject" : "1234567890123456789",
以及生成它的服务器端数据类型:
private String stringObject = "This is a string.";
private int integerPrimitive = -3;
private Integer intergerObject = 3333;
private long longPrimitive = 1234567890123456789L;
private Long longObject = 1234567890123456789L;
我编写了一个TypeAdapter来处理Long,但似乎在反序列化过程中,GSON不会查看目标变量,而是查看JSON本身。换句话说:它仍然似乎为Long / long调用String TypeAdapter,但至少我的TypeAdapter中的断点永远不会到达(尽管也可能是反射的工件)。这是可能的还是我的TypeAdapter还有其他问题? GSON如何确定它调用的适配器。
public class LongTypeAdapter extends TypeAdapter<Long> {
// Long/long is converted to String by AppEngine 0L -> "0"
@Override public void write(JsonWriter writer, Long value) throws IOException {
if (value == null) {
writer.nullValue();
return;
}
String text = "\"" + String.valueOf(value) + "\"";
writer.value(text);
}
@Override public Long read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
String text = reader.nextString();
text = text.replaceAll("\"", "");
Long value = Long.parseLong(text);
return value;
}
}
我已调试到GSON并且我的适配器已正确注册,因此我很可能会在此处排除注册问题。
这是适配器的注册方式:
public class Backend {
// Singleton
private static volatile BackendInterface service = null;
private Backend() {} // exists only to defeat instantiation
public static BackendInterface api() {
if (service == null) { // lazy initialization
final Gson gson = new GsonBuilder()
.registerTypeAdapter(Long.class, new LongTypeAdapter())
.create();
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(Constants.BACKEND_API_ENDPOINT)
.setClient(new OkClient())
.setLogLevel(RestAdapter.LogLevel.FULL) // TODO remove full logging for production
.setConverter(new GsonConverter(gson))
.build();
service = restAdapter.create(BackendInterface.class);
}
return service;
}
}
以下是我如何使用它:
Test test = Backend.api().getTest(2L);
答案 0 :(得分:0)
你必须注册新型适配器:
final Gson gson = new GsonBuilder().registerTypeAdapter(Long.class,
new LongTypeAdapter()).create();
我希望有帮助