如何将JSON挑选到Java对象

发布于 2025-01-17 14:58:32 字数 3645 浏览 0 评论 0原文

我正在从 Spring Boot 后端应用程序向 API 发出请求。我已经能够将我的对象序列化为 JSON 并向 API 发送 POST 请求。请求成功,我已经能够从服务器获取 Json 格式的响应。当我尝试反序列化对 Java 对象的响应时,就会出现问题。

这是我的 java 界面。

 public interface MyApi{
    ....

    BeneficiaryOnBoardingResponse onBoardBeneficiary(BeneficiaryOnBoardingRequests 
      beneficiaryOnBoardingRequests);
    ....
}

这是我的 MyApiServiceImpl

public class MyApiServiceImpl extends MyApi{

    private final ConfigFIle configFIle;
    private final OkHttpClient okHttpClient;
    private final ObjectMapper objectMapper;

public MyApiServiceImpl(ConfigFIle configFIle, OkHttpClient okHttpClient, ObjectMapper 
    objectMapper) {
    this.configFIle = configFIle;
    this.okHttpClient = okHttpClient;
    this.objectMapper = objectMapper;
}

@Override
public BeneficiaryOnBoardingResponse onBoardBeneficiary(BeneficiaryOnBoardingRequests 
    beneficiaryOnBoardingRequests) {
    AccessTokenResponse accessTokenResponse = getAccessToken();


    String jsonRequest = HelperUtility.toJson(beneficiaryOnBoardingRequests);
    log.info(String.format("Request Body %s", jsonRequest));

    RequestBody body = RequestBody.create(JSON_MEDIA_TYPE,
            Objects.requireNonNull(HelperUtility.toJson(beneficiaryOnBoardingRequests)));
    Request request = new Request.Builder()
            .url(configFIle.getBeneficiaryOnBoardingEndpoint())
            .post(body)
            .addHeader(AUTHORIZATION_HEADER_STRING, String.format("%s %s",
                    BEARER_AUTH_STRING, accessTokenResponse.getAccessToken()))
            .build();


    try {
        Response response = okHttpClient.newCall(request).execute();
        assert response.body() != null;
        log.info("====REGISTER CUSTOMER RESPONSE BODY====");
        log.info(String.format("%s", response.body().string()));
        //Deserialize to Java object;
        String json = response.body().string();
        log.info(String.format("%s", json));
        return objectMapper.readValue(response.body().string(), 
           BeneficiaryOnBoardingResponse.class);
       } catch (IOException ex) {
          log.error(String.format("Unable to register customer -> %s", 
          ex.getLocalizedMessage()));
          return null;
    }
}
}

这是我的控制器

@RestController
@RequestMapping("/v1/customer")
public class CustomerRegistrationController {

   private final MyApi myApi;
   private final ObjectMapper objectMapper;
   private final AcknowledgeResponse acknowledgeResponse;

@Autowired
public CustomerRegistrationController(MyApi myApi, 
    ObjectMapper objectMapper, AcknowledgeResponse acknowledgeResponse) 
  {
    this.myApi= myApi;
    this.objectMapper = objectMapper;
    this.acknowledgeResponse = acknowledgeResponse;
}

@PostMapping(path = "/register-customer",produces = "application/json")
public ResponseEntity<BeneficiaryOnBoardingResponse> registerCustomer(
        @RequestBody BeneficiaryOnBoardingRequests 
     beneficiaryOnBoardingRequests
        ){
     return ResponseEntity.ok(
         myApi.onBoardBeneficiary(beneficiaryOnBoardingRequests));
    }
  }

这是发生异常的地方。我已经使用 jackson 将 Json 反序列化为 java 对象。 return objectMapper.readValue(response.body().string(), BeneficiaryOnBoardingResponse.class);

这是日志中的错误 2022-03-29 23:19:33.161 错误 15564 --- [nio-8080-exec-2] oaccC[.[.[/].[dispatcherServlet] : servlet [dispatcherServlet] 的 Servlet.service()在路径 [] 的上下文中抛出异常 [请求处理失败;嵌套异常是 java.lang.IllegalStateException:已关闭] 其根本原因

提前致谢

I'm making a request to an API from my spring boot backend application. I have been able to serialize my object to JSON and send a POST request to the API. The request goes successful and I've been able to get a response from the server in Json format.The issue arises when I try to deserialize my response to Java object.

Here is my java Interface.

 public interface MyApi{
    ....

    BeneficiaryOnBoardingResponse onBoardBeneficiary(BeneficiaryOnBoardingRequests 
      beneficiaryOnBoardingRequests);
    ....
}

Here is my MyApiServiceImpl

public class MyApiServiceImpl extends MyApi{

    private final ConfigFIle configFIle;
    private final OkHttpClient okHttpClient;
    private final ObjectMapper objectMapper;

public MyApiServiceImpl(ConfigFIle configFIle, OkHttpClient okHttpClient, ObjectMapper 
    objectMapper) {
    this.configFIle = configFIle;
    this.okHttpClient = okHttpClient;
    this.objectMapper = objectMapper;
}

@Override
public BeneficiaryOnBoardingResponse onBoardBeneficiary(BeneficiaryOnBoardingRequests 
    beneficiaryOnBoardingRequests) {
    AccessTokenResponse accessTokenResponse = getAccessToken();


    String jsonRequest = HelperUtility.toJson(beneficiaryOnBoardingRequests);
    log.info(String.format("Request Body %s", jsonRequest));

    RequestBody body = RequestBody.create(JSON_MEDIA_TYPE,
            Objects.requireNonNull(HelperUtility.toJson(beneficiaryOnBoardingRequests)));
    Request request = new Request.Builder()
            .url(configFIle.getBeneficiaryOnBoardingEndpoint())
            .post(body)
            .addHeader(AUTHORIZATION_HEADER_STRING, String.format("%s %s",
                    BEARER_AUTH_STRING, accessTokenResponse.getAccessToken()))
            .build();


    try {
        Response response = okHttpClient.newCall(request).execute();
        assert response.body() != null;
        log.info("====REGISTER CUSTOMER RESPONSE BODY====");
        log.info(String.format("%s", response.body().string()));
        //Deserialize to Java object;
        String json = response.body().string();
        log.info(String.format("%s", json));
        return objectMapper.readValue(response.body().string(), 
           BeneficiaryOnBoardingResponse.class);
       } catch (IOException ex) {
          log.error(String.format("Unable to register customer -> %s", 
          ex.getLocalizedMessage()));
          return null;
    }
}
}

Here is my controller

@RestController
@RequestMapping("/v1/customer")
public class CustomerRegistrationController {

   private final MyApi myApi;
   private final ObjectMapper objectMapper;
   private final AcknowledgeResponse acknowledgeResponse;

@Autowired
public CustomerRegistrationController(MyApi myApi, 
    ObjectMapper objectMapper, AcknowledgeResponse acknowledgeResponse) 
  {
    this.myApi= myApi;
    this.objectMapper = objectMapper;
    this.acknowledgeResponse = acknowledgeResponse;
}

@PostMapping(path = "/register-customer",produces = "application/json")
public ResponseEntity<BeneficiaryOnBoardingResponse> registerCustomer(
        @RequestBody BeneficiaryOnBoardingRequests 
     beneficiaryOnBoardingRequests
        ){
     return ResponseEntity.ok(
         myApi.onBoardBeneficiary(beneficiaryOnBoardingRequests));
    }
  }

This is where the exception occures. I have used jackson to deserialize the Json to a java object.
return objectMapper.readValue(response.body().string(), BeneficiaryOnBoardingResponse.class);

and this is the error from the logs
2022-03-29 23:19:33.161 ERROR 15564 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: closed] with root cause

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文