API响应的返回值有问题。我有型号:
public class MfConfig {
public List<Multiplications> multiplications;}
我通过REST ASSURED和Jackson一起运行测试。测试返回响应,在响应中我有许多对象。在这些对象中,我有一个字段(键(返回了几次。当字段的返回值为空时,字段是一个数组,但当字段有值时,字段就是一个对象:
"multiplications": [
]
"multiplications": {
"id": 133389
}
当我有上面这样的模型时,我得到了:
org.json.JSONException: JSONObject["multiplications"] is not a JSONObject.
当我将型号更改为:
public class MfConfig {
public Multiplications multiplications;}
我得到了:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type 'test.Multiplications` from Array value (token `JsonToken.START_ARRAY`)
在测试中我使用:
given(requestSpecification)
.baseUri(endpoint)
.when()
.get()
.then()
.extract()
.as((Multiplication.class)
我可以将I更改为:
given(requestSpecification)
.baseUri(endpoint)
.when()
.get()
.then()
.extract()
.as((Multiplication[].class)
但我用Object的响应出现了错误。反之亦然。在模型中,我尝试过类似的东西:
@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
public Multiplications multiplications;
或
@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
public List<Multiplications> multiplications;
但它不起作用。也许有人对响应有想法,一个字段有不同的类型,比如对象和数组?
- 设置POJO
@Data
public class MfConfig {
@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
public List<Multiplications> multiplications;
}
@Data
public class Multiplications {
public int id;
}
- 反序列化
MfConfig mfConfig = given(requestSpecification)
.baseUri(endpoint)
.when()
.get()
.then()
.extract()
.as(MfConfig.class)
- 结果
MfConfig(multiplications=[])
MfConfig(multiplications=[Multiplications(id=133389)])