开发者

deserialize json field into plain string with gson

开发者 https://www.devze.com 2023-02-17 22:47 出处:网络
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 potential

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", 
        ...}
}

How can i tell gson to ignore the object value s开发者_开发技巧o 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.


Just declare it as of type JsonObject

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

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


I don't know if your problem is solved. I ran into a similar question and here it is how I worked it out:

JsonDeserializer allows you to make you own adapter to deserialize that **:

class JavaBeanDeserializer implements JsonDeserializer<JavaBeanObject>() {
    public JavaBeanObject fromJson(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    // return JavaBeanObject built using your logic.
}

You've to register JavaBeanDeserializer to Gson object when building it:

Gson gson = new GsonBuilder().registerTypeAdapter(JavaBeanObject.class, new JavaBeanDeserializer()).create();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号