从外部 API 检查不存在的数据

问题描述 投票:0回答:1

我正在调用一个外部API,它会给出如下所示的响应,我在代码中使用了它

    {
    "totalInvestedAmount": 10500.0,
    "totalCurrentValue": 10550.0,
    "otherInfo": {
             "firstData" : [             
                        "hi",
                        "hello",
                        "bye"
                   ],
           
              "secondData": "secondData",
              "thirdData": {
                         "a": "aaa",
                         "b": "bbb"
                     }
              }

}

otherInfo 是一个具有 firstData(String[]) 和 secondData(String) 的对象。

到目前为止,上面的响应通常是这样的,如果响应中的 firstDatasecondData 曾经是 empty,那么它看起来像

 {
    "totalInvestedAmount": 10500.0,
    "totalCurrentValue": 10550.0,
    "otherInfo": {
             "firstData" : [ "", ""],           
              "secondData": ""
}

我在代码中对 otherInfo 对象和 secondData 进行了类似 Objects::nonNull 的检查。

外部API响应新变化

但是从现在开始,由于外部API系统的一些变化,响应将开始像-

如果 firstData 包含空值或 secondDataempty,则响应将不包含这些字段。

例如1。如果 firstData 包含空值。反应会是

{
    "totalInvestedAmount": 10500.0,
    "totalCurrentValue": 10550.0,
    "otherInfo": {           
              "secondData": "sample text"
}

Eg2 如果 secondData 为空,则响应将为

{
    "totalInvestedAmount": 10500.0,
    "totalCurrentValue": 10550.0,
    "otherInfo": {           
              "firstData": [ "word1", "word2"]
}

Eg3 如果 firstDatasecondData - 两者都为空,则响应将不包含 otherInfo 对象。会是这样的:

 {
    "totalInvestedAmount": 10500.0,
    "totalCurrentValue": 10550.0,
  
}

所以,我想问我现在应该在我的代码中包含什么类型的检查,以便可以与上述三个示例一起使用。请在此处放置示例解决方案。

java spring spring-boot java-8
1个回答
1
投票

未返回的字段为空。因此,Objects.isNull/nonNull 检查将适用于这些字段

© www.soinside.com 2019 - 2024. All rights reserved.