微服务间DTO交互报JSON解析错误(error字段未识别),求修复方案
微服务间JSON解析错误:Unrecognized field "error" 解决方法
问题详情
出现JSON解析错误:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized field "error" not marked as ignorable
两个微服务间使用ProfileResource作为请求和响应DTO,请求发送代码如下:
HttpEntity<ProfileResource> requestEntity = new HttpEntity<>(request); ResponseEntity<ProfileResource> response = null; try { response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, ProfileResource.class, Collections.emptyMap()); } catch (Exception ex) {.....}
DTO定义:
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.NON_PRIVATE) @JsonIgnoreProperties(ignoreUnknown = false) public class ProfileResource { private String firstName; private Error error; ....... } // Error类定义 @JsonIgnoreProperties(ignoreUnknown = true) @Data @JsonInclude(JsonInclude.Include.NON_EMPTY) public class Error implements ErrorCode { private String code; }
接收方微服务返回错误:
org.springframework.web.client.HttpClientErrorException$BadRequest: 400 : "{\"error\":{\"code\":\"5023\",\"message\":\"You submitted a request that is not parseable.: field 'error' not recognized\",
问题:如何解决该问题?是否需要忽略error字段?
解决方案
给ProfileResource中的error字段添加@JsonInclude(JsonInclude.Include.NON_NULL)注解,确保当error为null时不会被序列化为JSON字段发送给接收方:
@JsonInclude(JsonInclude.Include.NON_NULL) private Error error;
内容的提问来源于stack exchange,提问作者Peter Penzov
相关产品推荐
相关产品推荐

