我在Java 7中使用Gson解析器。我想将我的一个属性保存为原始JSON字符串,以便稍后将其反序列化为所需的类。
示例输入JSON:
{
"foo":"bar",
"body":["blah"]
}
或
{
"foo":"bar",
"body":{"a":"b"}
}
反序列化为这样的类:
public class Message {
public String foo;
public String bar; //I want this to be a raw JSON string, not parsed
}
代码:
String input = "{\"foo\":\"bar\", \"body\":[\"blah\"]}";
Message message = gson.fromJson(input, Message.class);
message.foo; //"bar"
message.body; //"[\"blah\"]"
这可能吗?
更新:
我目前正在这样做,但如果它可以更清洁"那就太好了。并以某种方式使用原生String
类型......
public class Message {
public String foo;
public JsonString body;
}
public static class JsonString {
public String body;
}
public static class JsonStringDeserializer implements JsonDeserializer<JsonString> {
@Override
public JsonString deserialize(JsonElement json, Type type, JsonDeserializationContext context) {
JsonString a = new JsonString();
a.body = json.toString();
return a;
}
}
我不喜欢这样的事情是我必须像这样使用反序列化的对象:
Message message = gson.fromJson(input, Message.class);
//notice how i have to use the inner string
SomeClass cls = gson.fromJson(message.body.body, SomeClass.class);
答案 0 :(得分:2)
如果您不介意将body
属性声明为Object
而不是String
来解决JSON解码问题;你可以做到以下几点。
JSONRawString
的注释定义:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface JSONRawString {
}
Message
类:
public class Message {
public String foo;
@JSONRawString
public Object body;
}
反序列化器:
public class JSONRawStringDeserializer<T> implements JsonDeserializer<T> {
@Override
public T deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
//We decode using the normal deserializer; but will run over all the fields and check if our annotation exists. This is a bit hacky; but should work if you don't mind declaring your objects which you'd like to maintain as deserialized as Object.
T serializedObject = new Gson().fromJson(jsonElement, type);
Field[] fields = serializedObject.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.getAnnotation(JSONRawString.class) != null) {
try {
String fieldName = field.getName();
if(field.getAnnotation(SerializedName.class) != null) {
fieldName = field.getAnnotation(SerializedName.class).value();
}
String element = new Gson().toJson(jsonElement.getAsJsonObject().get(fieldName).toString());
field.set(serializedObject, element);
} catch(IllegalAccessException e) {
throw new JsonParseException(e);
}
}
}
return serializedObject;
}
}
最后在Main
:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Main {
public static void main(String[] args) {
Gson gson = new GsonBuilder()
.registerTypeAdapter(Message.class, new JSONRawStringDeserializer<Message>())
.create();
String input = "{\"foo\":\"bar\", \"body\":[\"blah\"]}";
Message message = gson.fromJson(input, Message.class);
System.out.printf("message.foo: %s, message.body: %s", message.foo, message.body);
}
}
导致message.foo: bar, message.body: "[\"blah\"]"
这有点像hacky;因为我们用我们自己的方法覆盖了Gson吐出的东西;而且我不认为这是递归的。希望它会引导您找到解决方案。
答案 1 :(得分:1)
最好不要使用JsonDeserializer
,而是使用gson的TypeAdapter提供的更新的JsonReader
/ JsonWriter
接口。
请在此处查看我的回答:https://stackoverflow.com/a/50537019/332798