利用多态性从JSON生成对象

huangapple 未分类评论44阅读模式
英文:

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 have this JSON and I want to generate objects with it.

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

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

{
  &quot;parameters&quot;: {
     &quot;email&quot;:&quot;example@example.com&quot;
  }
}

Also, I could have

{
&quot;parameters&quot;: {
		&quot;orderNumber&quot;: &quot;PQL7648194AAAAA&quot;,
		&quot;lastName&quot;: &quot;RIVERO&quot;
    }
}

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 &lt;T&gt; T buildBodyFromJson(String filePath, Class&lt;T&gt; 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 &quot;Unrecognized field ... not marked as ignorable &quot;.

答案1

得分: 0

我理解您并不真正需要两个分开的类,问题是您需要生成一个不包含空/空字段的请求正文。好的,有一个注释可能会对您有所帮助。

创建一个参数的单一类,包含所有的3个属性,并使用 @JsonInclude(JsonInclude.Include.NON_EMPTY) 进行注释。

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

这个注释会使空的或者为null的字段不会出现在您正在创建的请求正文中。

英文:

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.

huangapple
  • 本文由 发表于 2020年4月4日 06:38:25
  • 转载请务必保留本文链接:https://java.coder-hub.com/61021451.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定