我有一个接受JSON的Web服务,我使用GSON将JSON字符串转换为POJO。
POJO示例:
class POJO{
AtomicReference<String> property;
}
JSON字符串示例:
{&#34;属性&#34;:&#34; VAL&#34;}
然而,当GSON解析JSON字符串时,它会抛出JSONSyntaxException,因为它期望JSON字符串为:
{&#34;属性&#34; {&#34;值&#34;:&#34; VAL&#34;}}
我是否只需要使用非并发变量编写POJO(POJO2)的副本,然后使用POJO2值使用并发变量初始化我的POJO(POJO1)?或者,有没有办法让GSON将AtomicReference变量视为String?
如果我使用前者,它会消除GSON的功能,从动态输出json字符串中的对象。
答案 0 :(得分:1)
我再次咨询了Google,发现this answer制作了TypeAdapters。所以,我为它推出了自己的类型适配器。我还在我的POJO类中使用了AtomicLong等其他Atomic对象,这种方法也适用于它。
class AtomicStringTypeAdapter extends TypeAdapter<AtomicReference<String>> {
@Override
public AtomicReference<String> read(JsonReader in) throws IOException {
AtomicReference<String> value = null;
JsonParser jsonParser = new JsonParser();
JsonElement je = jsonParser.parse(in);
if (je instanceof JsonPrimitive) {
value = new AtomicReference<String>();
value.set(((JsonPrimitive) je).getAsString());
} else if (je instanceof JsonObject) {
JsonObject jsonObject = (JsonObject) je;
value = new AtomicReference<String>();
value.set(jsonObject.get("value").getAsString());
}
return value;
}
@Override
public void write(JsonWriter out, AtomicReference<String> value) throws IOException {
if (value != null) {
out.beginObject();
out.name("value").value(value.get());
out.endObject();
}
}
}