简体   繁体   English

有什么方法可以跳过不兼容的 class 成员的反序列化?

[英]Any way to skip deserialization of class members which are incompatible?

I am calling an external API through RestTemplate.我正在通过 RestTemplate 调用外部 API。 There is one parameter in the response structure that is dynamic ie returns two types of values, it returns a Json structure in the success case (status = true) and an empty string "" in case of failure (status = false).响应结构中有一个参数是动态的,即返回两种类型的值,成功时返回 Json 结构(status = true),失败时返回空字符串“”(status = false)。 The RestTemplate is throwing exception in failure case as the string is not able to deserialze into the class object. RestTemplate 在失败情况下抛出异常,因为字符串无法反序列化到 class object。 This is my response class:这是我的回复 class:

public class Response {
    private boolean status;
    private String message;
    private DynamicClass data;
}
public static class DynamicClass {
    private String id;
    private String createdDate;
}

This call is throwing exception:此调用引发异常:

ResponseEntity<Response> responseEntity = restTemplate.postForEntity(url, httpRequest, Response.class);

Exception:例外:

org.springframework.web.client.RestClientException: Error while extracting response for type [class com.example.data.Response] and content type [application/json;charset=utf-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.example.data.Response$DynamicClass` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value (''); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.example.data.Response$DynamicClass` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('')
 at [Source: (sun.net.www.protocol.http.HttpURLConnection$HttpInputStream); line: 1, column: 78] (through reference chain: com.example.data.Response["data"])
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:119)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:998)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:981)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:741)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:674)
.
.
.
Caused by: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.example.data.Response$DynamicClass` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value (''); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.example.data.Response$DynamicClass` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('')
 at [Source: (sun.net.www.protocol.http.HttpURLConnection$HttpInputStream); line: 1, column: 78] (through reference chain: com.example.data.Response["data"])

Is there any way I can tell the parser to skip the deserialization of that member if it is not compatible as I don't need that empty string anyway?如果它不兼容,我有什么办法可以告诉解析器跳过该成员的反序列化,因为我不需要那个空字符串? Or any other workaround for this problem?或者这个问题的任何其他解决方法?

  • Option 1::选项1::

If you are using Spring, the simplest way to override the default configuration is to define an ObjectMapper bean and to mark it as @Primary:如果您使用的是 Spring,覆盖默认配置的最简单方法是定义一个 ObjectMapper bean 并将其标记为 @Primary:

Check:: https://www.baeldung.com/spring-boot-customize-jackson-objectmapper检查:: https://www.baeldung.com/spring-boot-customize-jackson-objectmapper

@Bean
@Primary
public ObjectMapper objectMapper() {

    return new ObjectMapper()
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      .configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,true);

}
  • Option 2:: Convert the response to string and check for empty body and do the needful by converting the string to class object using object mapper.选项 2::将响应转换为字符串并检查空正文并通过使用 object 映射器将字符串转换为 class object 来执行必要的操作。

    ResponseEntity responseEntity = restTemplate.postForEntity(url,httpRequest, String.class); ResponseEntity responseEntity = restTemplate.postForEntity(url,httpRequest, String.class);

     if(.StringUtils.isBlank(responseEntity;getBody())) { Gson gson = new Gson(). Response res= gson.fromJson(responseEntity,getBody(). Response;class); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有什么方法可以保存“静态成员”的 state 吗? - Is there any way by which I can save the state of `static members`? Jackson 映射器跳过 class 名称(反序列化问题) - Jackson mapper skip class name (deserialization issue) 有什么方法可以防止杰克逊场反序列化吗? - Is there any way to prevent field from deserialization in jackson? 哪些成员不是在子类中继承的? - Which members are not inherited in a child class? 有什么方法可以创建从Android中的Canvas扩展的类吗? - Is there any way to create class which extends from Canvas in Android? 有什么方法可以模拟其他 class 中的私有方法 - Is there any way to Mock the private method , which is there in other class 是否有任何Java函数或util类以这种方式舍入:func(3/2)= 2? - Is there any Java function or util class which does rounding this way: func(3/2) = 2? 有什么方法可以与生成意图并从扩展IntentService类的类发送该意图的类进行通信? - Is there any way by which we can communicate back to the class which generated an intent and sent it from a class which extends IntentService class? 有什么办法可以在不中断反序列化过程的情况下忽略JsonProcessingException - Is there any way to ignore JsonProcessingException without breaking deserialization process Gson反序列化跳过一个引用 - Gson deserialization skip one quotation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM