使用gson将json字段反序列化为纯字符串

问题描述:

我试图将一个json对象反序列化成一个java bean。
我面临的主要问题是我想将json字符串的字段 object 作为纯字符串处理,即使它包含可能正确的字符串json对象。
json结构如下所示:

I am trying to deserialize a json object into a java bean. The main issue I am facing is that I'd like to treat the field object of the json string as a plain string, even if it contains a potentially correct json object. The json structure is like this:

{
    "type":"user",
    "object":{
        "id":"1", 
        ...}
}

我如何告诉gson忽略对象值,以便它不会被反序列化到一个对象中?我只想将它映射到我的bean中的一个普通的 String 字段,这样我就可以为它设置正确的反序列化,一旦我从 type 字段。

How can i tell gson to ignore the object value so that it doesn't get deserialized into an object? I'd like it only to be mapped to a plain String field in my bean so that I can dispose a proper deserialization for it, once I got the type from the type field.

只要将它声明为JsonObject类型即可

Just declare it as of type JsonObject

class ExampleJsonModel {
    @SerializedName("type")
    public String type;

    @SerializedName("object")
    public JsonObject object;
}