Search code examples
javajsongsonpojo

How to set different type for variable in POJO than expected while deserializing json using gson


I want to convert JSON object back to Person object java, but field key can be String or String[]. So I am getting the following error: java.lang.IllegalStateException: Expected STRING but was BEGIN_ARRAY at path $.key

Example Json files:

{
  "type":"set",
  "key":"person",
  "value":{
    "name":"Elon Musk",
    "car":{
      "model":"Tesla Roadster",
      "year":"2018"
    },
    "rocket":{
      "name":"Falcon 9",
      "launches":"87"
    }
  }
}

or

{"type":"get","key":["person","name"]}
JsonObject jsonObject = new JsonParser().parse(input.readUTF()).getAsJsonObject();

Gson gson = new Gson();

Person person = gson.fromJson(jsonObject, Person.class);

@Getter
@Setter
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Person  {
String type;
String key;
Value value;
}

Solution

  • May be you need to create custom deserializer like this:

    class MyTypeModelDeserializer implements JsonDeserializer<MyBaseTypeModel> {
    
        @Override
        public MyBaseTypeModel deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
                throws JsonParseException {
    
            JsonObject jsonObject = json.getAsJsonObject();
    
            JsonElement jsonType = jsonObject.get("type");
            String type = jsonType.getAsString();
    
            MyBaseTypeModel typeModel = null;     
    
            if("type1".equals(type)) {
                typeModel = new Type1Model();
            } else if("type2".equals(type)) {
                typeModel = new Type2Model();
            }
            // TODO : set properties of type model
    
            return typeModel;
        }
    }