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.
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.
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.
As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With