deserialize json field into plain string with gson

↘锁芯ラ 提交于 2019-12-18 21:52:30

问题


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 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.


回答1:


Just declare it as of type JsonObject

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

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



回答2:


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();


来源:https://stackoverflow.com/questions/5377578/deserialize-json-field-into-plain-string-with-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!