【问题标题】:How to add list of objects class to arraylist?如何将对象类列表添加到arraylist?
【发布时间】:2019-05-29 19:21:37
【问题描述】:

需要将有错误的对象列表添加到 arraylist 主体。 我试图将response.getErrors() 设置为response.getBody() 的代码:

String jsonResponse = restTemplate.postForObject(url, requestBody, String.class);
JavaType valueType = mapper.getTypeFactory().constructParametricType(ResponseContainer.class, type);
ResponseContainer<ResponseType> response = mapper.readValue(jsonResponse, valueType);
        // TODO if error != null put errors to body
if (response.getErrors() != null) {
    response.getBody().addAll(response.getErrors());
}
return response.getBody();

模型类:

@ApiModelProperty(notes = "Список параметров сообщения")
List<T> body = new ArrayList<T>();

@ApiModelProperty(notes = "Список ошибок")
List<ResponseError> errors;

错误是:

Error:(70, 35) java: no suitable method found for add(java.util.List<com.infin.it.integrator.impl.base.ResponseError>)
method java.util.Collection.add(ResponseType) is not applicable
  (argument mismatch; java.util.List<com.infin.it.integrator.impl.base.ResponseError> cannot be converted to ResponseType)
method java.util.List.add(ResponseType) is not applicable
  (argument mismatch; java.util.List<com.infin.it.integrator.impl.base.ResponseError> cannot be converted to ResponseType)

【问题讨论】:

  • 这真的是完整的错误信息吗?
  • 是的,完全错误在 response.getErrors()
  • 不,我的意思是“在列表中无法应用”完整的错误消息?
  • 哦,对不起。错误是:无法将 List 中的 addAll (java.util.Collection extends ResponseType>) 应用于 (java.util.List)
  • 看起来 com.infin.it.integrator.impl.base.ResponseError 没有从 ResponseType 继承。如果这两个列表都是 ´response 对象的一部分,为什么你还需要加入它们?

标签: java spring spring-boot jackson


【解决方案1】:

我将@ApiModelProperty(notes = "Список ошибок") List<ResponseError> errors; 的类型更改为List&lt;T&gt; errors = new ArrayList&lt;T&gt;(); 很快我添加了来自对我的ResponseBaseModel.class 的回复的字段,以获取该字段并显示错误。

这解决了我的问题。感谢大家的建议。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-26
    • 2019-02-18
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    相关资源
    最近更新 更多