简体   繁体   中英

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;
}

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM