Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deserialize json field into plain string with gson

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.

like image 915
mox601 Avatar asked Mar 21 '11 12:03

mox601


People also ask

How do I deserialize JSON with Gson?

Deserialization in the context of Gson means converting a JSON string to an equivalent Java object. In order to do the deserialization, we need a Gson object and call the function fromJson() and pass two parameters i.e. JSON string and expected java type after parsing is finished. Program output.

How to convert JSON into object using Gson?

Call the Gson. fromJSon(json, UserDetails. class) to convert the given JSON String to object of the class given as the second argument. This method returns a Java object whose fields are populated using values given in JSON String.

Does Gson ignore extra fields?

As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.

How to deserialize JSON String to object in Java?

We can deserialize a JSON to Java object using the deserialize() method of JSONDeserializer class, it takes as input a json string and produces a static typed object graph from that json representation.


2 Answers

Just declare it as of type JsonObject

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

    @SerializedName("object")
    public JsonObject object;
}
like image 95
GaRRaPeTa Avatar answered Oct 30 '22 15:10

GaRRaPeTa


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();
like image 45
Joao Avatar answered Oct 30 '22 16:10

Joao