[英]How to read JSON String attribute into custom class object using Gson?
When reading a JSON :读取 JSON 时:
{"field":"value"}
into a String field :到一个字符串字段:
public class Test {
private String field;
}
using Gson.fromJson
it works as intended and the member String field gets the value "value".使用Gson.fromJson
它按预期工作,成员 String 字段获取值“value”。
My question is, is there a way to read the same JSON into a custom class so that the custom class object can be constructed with the String value?我的问题是,有没有办法将相同的 JSON 读入自定义类,以便可以使用 String 值构造自定义类对象? eg例如
public class Test {
private MyField<String> field;
}
public class MyField<T> {
private T value;
public MyField(T v) {
value = v;
}
}
The reason being the String class is final and cannot be extended, yet I don't want the JSON to be changed into this :原因是 String 类是最终的并且无法扩展,但我不希望将 JSON 更改为:
{"field":{"value":"value"}}
If there is a way to extend the String class, it is the best.如果有扩展String类的方法,那就最好了。 Otherwise, will need a way for Gson to read string into a custom class that can be constructed by string.否则,将需要一种方法让 Gson 将字符串读入可以由字符串构造的自定义类。 Something to do with writing a custom TypeAdapter
?与编写自定义TypeAdapter
什么关系?
You can use custom JsonDeserializer
, JsonSerializer
.您可以使用自定义JsonDeserializer
、 JsonSerializer
。 Here is simple demo version:这是简单的演示版本:
static class MyFieldAsValueTypeAdapter<T> implements
JsonDeserializer<MyField<T>>, JsonSerializer<MyField<T>> {
private Gson gson = new Gson();
@Override
public MyField<T> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
JsonObject obj = new JsonObject();
obj.add("value", json);
return gson.fromJson(obj, typeOfT);
}
@Override
public JsonElement serialize(MyField<T> src, Type typeOfSrc,
JsonSerializationContext context) {
return context.serialize(src.getValue());
}
}
public static void main(String[] args) {
GsonBuilder b = new GsonBuilder();
b.registerTypeAdapter(MyField.class , new MyFieldAsValueTypeAdapter());
Gson gson = b.create();
String json = "{\"field\":\"value1\"}";
Test test = gson.fromJson(json, Test.class);
}
Be careful with internal Gson gson = new Gson()
.小心内部Gson gson = new Gson()
。 If you have some other setup, you will need to register it on internal version or pass default MyField deserializer/serializer to your custom implementation.如果您有其他设置,则需要在内部版本上注册它或将默认 MyField 解串器/串行器传递给您的自定义实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.