【问题标题】:Checking if received JSON has necessary values in Java检查收到的 JSON 在 Java 中是否具有必要的值
【发布时间】:2019-03-06 05:04:33
【问题描述】:

我有一个接收 JSON 文件的 API 端点,并且我正在从这些文件中创建一个对象。我还有另一个预先存在的对象,我正在尝试检查接收到的 JSON 中的某些值是否与我现有对象中的某些值匹配。如果字段匹配,我将继续进一步处理文件,否则我将废弃它。到目前为止,我的想法只是让 if 语句检查每个值,但有没有更好的方法来做到这一点?或者 if 语句可以吗?

仅使用 if 语句的非常快速的代码示例。

public boolean compareObjects(recievedObject, existingObject) {
    if( !(recievedObject.getName().equals(existingObject.getName()))) {
        //true
    } else if( !(recievedObject.getLocation().equals(existingObject.getLocation())) ) {
        return false;
    }
    // else if ... etc 

    return true;
}

请注意,我并不是要检查接收到的文件是否包含所有必需的 JSON 字段,只是检查一些特定字段是否具有某些值。

编辑:

JSON 将是一个非常扁平的结构,例如

{
    "name": "name",
    "location": "location",
    ...
}

所以我的对象将是非常基本的

public class recievedObject {
    String location;
    String name;

    public String getLocation() {
        return location;
    }

    public String getName() {
        return name;
    }
}

【问题讨论】:

  • 您应该展示一个可以作为解决方案起点的示例代码。
  • 您至少需要描述一下您的 JSON 文档结构。
  • “更好的方法”是什么意思?如果您有一种可行的方法,并且它可以按您的需要运行并满足您的所有要求,那么问题出在哪里?

标签: java json


【解决方案1】:

你可以做的就是创建一些验证抽象来避免大量的 it-else 语句。

interface Validator<A, B> {
  boolean validate(A receivedObject, B existingObject);
}

然后为每个if 创建Validator 的新实现。

class NameValidator implements Validator<Expeceted, Received> {
  @Override
  public boolean validate(Expeceted receivedObject, Received existingObject) {
    return existingObject.getName().equals(receivedObject.getName());
  }
}   

class LocationValidator implements Validator<Expeceted, Received> {
  @Override
  public boolean validate(Expeceted receivedObject, Received existingObject) {
    return existingObject.getLocation().equals(receivedObject.getLocation());
  }
}

您可以创建此类验证器的列表

List<Validator<Expeceted, Received>> validators = Arrays.asList(
  new NameValidator(),
  new LocationValidator()
);

最后,您的 compare 方法可以简单地遍历所有验证器。

public boolean compareObjects(Received recievedObject, Expeceted expecetedObject) {
  for (Validator<Expeceted, Received> validation : validators) {
    if (! validation.validate(expecetedObject, recievedObject)) {
      return false;
    }
  }
  return true;
}

这样您以后可以简单地添加新的验证器并保持比较方法不变。

【讨论】:

    【解决方案2】:

    为您的类定义一个类似于 'equal' 的方法,并在端点检查 existingObject.check(receivedObject),将 import java.util.Objects 添加到您的类中

    public boolean check(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        RecievedObject receivedObject=(RecievedObject) o;
    
       //add based on the logic you want
        return Objects.equals(location, receivedObject.location) &&
                Objects.equals(name, receivedObject.name);
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 2021-06-17
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      相关资源
      最近更新 更多