助焊剂解码异常:意外字符(“ [”(代码91)):期望双引号开头字段名称

时间:2019-02-25 09:36:58

标签: json spring spring-webflux

当将 Flux JSON解码为 Java 对象时,出现以下异常:

2019-02-25 13:44:39.136 TRACE [{}] 25292 --- [reactor-http-nio-4] o.s.w.r.f.c.ExchangeFunctions            : [762021a9] Response 200 OK, headers={masked}
2019-02-25 13:44:39.195 ERROR [{}] 25292 --- [reactor-http-nio-4] r.M.C.2                                  : | onError(org.springframework.core.codec.DecodingException: JSON decoding error: Unexpected character ('[' (code 91)): was expecting double-quote to start field name; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('[' (code 91)): was expecting double-quote to start field name
 at [Source: UNKNOWN; line: 2, column: 3])
2019-02-25 13:44:39.196 ERROR [{}] 25292 --- [reactor-http-nio-4] r.M.C.2                                  : 
org.springframework.core.codec.DecodingException: JSON decoding error: Unexpected character ('[' (code 91)): was expecting double-quote to start field name; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('[' (code 91)): was expecting double-quote to start field name
 at [Source: UNKNOWN; line: 2, column: 3]
    at org.springframework.http.codec.json.Jackson2Tokenizer.tokenize(Jackson2Tokenizer.java:104) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]

按如下所示设置映射器编解码器属性不能解决问题:

mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

以下是 JSON 响应:

[
  {
    "id": "111",
    "description": "xyz"
  },
  {
    "id": "222",
    "description": "pqr"
  }
]

下面是WebClient的实现:

public Mono<List<ItemServiceResponse>> getItems(ItemServiceRequest itemServiceRequest) {
return webClient
        .post()
        .contentType(MediaType.APPLICATION_JSON)
        .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_STREAM_JSON.toString())
        .body(Mono.just(itemServiceRequest), ItemServiceRequest.class)
        .retrieve()
        .bodyToFlux(ItemServiceResponse.class)
        .collectList()
        .log();
}

这是Java对象:

@Builder 
@Data 
@AllArgsConstructor 
@NoArgsConstructor 
public class ItemServiceResponse { 
  private String id; 
  private String description; 
}

2 个答案:

答案 0 :(得分:0)

MongoDB (4.0.4)期望从您的 Json repsonse中将单个对象映射为ObjectMapper,因此是一个例外(映射器期望的是 quote )。

您应该更新ItemServiceResponse调用以映射WebClient中的array

ItemServiceResponse

答案 1 :(得分:0)

一个可怕的问题!!!我花了4-5天的时间弄清楚代码中的错误,然后尝试了所有排列组合,但没有任何效果。

但是伙计们,邮差是罪魁祸首,是的。

我得到的JSON的实际响应结构:

False == 0

这是格式错误的JSON。但是Postman正在以某种方式进行自动更正,并且给出了正确的响应,如问题中提到的JSON,并且我对响应的关注不多,因为状态码成功200。

幸运的是,我触发了Curl命令并找到了根本原因。请不要相信邮递员……更正不需要的东西真是太聪明了。