简体   繁体   中英

Generate objects from JSON with Polymorphism

I have this JSON and I want to generate objects with it.

{
  "responseId": "response-id",
  "session": "projects/project-id/agent/sessions/session-id",
  "queryResult": {
    "queryText": "End-user expression",
    "parameters": {
      "orderNumber": "PQL7648194AAAAA",
      "lastName": "RIVERO"
    },
    "action": "order",
    "allRequiredParamsPresent": true,
    "intent": {
      "name": "projects/project-id/agent/intents/intent-id",
      "displayName": "[InfoVuelo] Dia-hora de salida - datos de orden"
    },
    "languageCode": "es"
  },
  "originalDetectIntentRequest": {}
}

The fields of "parameters" are variable. For example for one situation parameters could be

{
  "parameters": {
     "email":"example@example.com"
  }
}

Also, I could have

{
"parameters": {
        "orderNumber": "PQL7648194AAAAA",
        "lastName": "RIVERO"
    }
}

I made a class Parameters and 2 classes( OrderNumberAndLastNameParams and EmailParams ) that extends Parameters

public class EmailParams implements Parameters {
    private String email;
}  

public class OrderNumberLastNameParams implements Parameters {
    private String orderNumber;

    private String lastName;
}

My method to create objects with a given JSON file

public static <T> T buildBodyFromJson(String filePath, Class<T> clazz) {
    ObjectMapper myMapper = new ObjectMapper();
    T jsonMapper = null;
    try {
      jsonMapper = myMapper.readValue(new ClassPathResource(filePath).getInputStream(), clazz);
    } catch (IOException e) {
      fail(e.getLocalizedMessage());
    }
    return jsonMapper;
  }

But when I try to build the object, It tries to instantiate Parameter object instead of children objects getting "Unrecognized field... not marked as ignorable " .

I'm understanding that you don't really need two separated classes, the problem is that you need to generate a requestbody with this object that doesn't have null / empty fields. Well, there is an annotation that may help you.

Create a single class for paramters with all the 3 properties and annotate with @JsonInclude(JsonInclude.Include.NON_EMPTY)

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Parameters  {
    private String email;
    private String orderNumber;
    private String lastName;
}  

This annotation makes empty or null fields to not appears on the requestbody that you're creating.

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