访问内部 json 字段并可选检查 null

Accessing internal json field with optional checking null

我有一个 json 这样的:

{
    "name": "car",
      "attributes": {
        "lon": 13,
        "lat": 15
    }
}

有时某些属性可以为空。

Optional<Attributes> op = Optional.ofNullable(json);

if (op.isPresent()) {
    Optional<Integer> opI = Optional.ofNullable(op.get().getLon());
   opI.ifPresent(....);
}

如何避免在多行中使用 Optional,有没有安全的方法来减少它。想象一下你有一个像这样的 json。

{"object1": {
    "object2": {
       "object3": {
           "object4: {

并且您需要访问 object4,但要检查之前的某些对象是否为 null,我的方法是使用 optional。这不是最好和更优雅的解决方案。

我可以使用可选和减少代码以优雅的方式做什么?

你只需要使用Optional.map,它会在可选为空时跳过你给它的代码

Integer lon = Optional.ofNullable(json).map(Attributes::getLon).orElse(null);

您可以将任意数量的中间 map() 调用链接到连续的可选值上。 map() 如果可选项为空,将跳过对您提供的函数的调用。

所以,对于你的另一个案例:

var object4 = Optional.ofNullable(mainObject)
                  .map(MainObject::getObject1)
                  .map(Object1:getObject2)
                  .map(Object2:getObject3)
                  .map(Object3:getObject4)
                  .orElse(null); //set object4 to null if anything was missing

牢记重要事项(来自链接的 JavaDocs):

If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.

因此,如果任何 getObjectN returns 为 null,则生成的可选值将为空。