从设置的 lombok 值中获取 属性

get property from set lombok value

您好,我一直在尝试弄清楚如何使用流从 Places 对象中获取 stateCode。我正在使用 lombok 来解​​析 json 对象,它看起来像这样:

{"post code": "90210", "country": "United States", "country abbreviation": "US", "places": [{"place name": "Beverly Hills", "longitude": "-118.4065", "state": "California", "state abbreviation": "CA", "latitude": "34.0901"}]}

我构建了一个 class 来像这样处理对象:

@lombok.Value
public class ZipCode {
  @JsonAlias("post code")
  private final String postalCode;
  private final  Set<Places> places;

  public ZipCode() {
    this.postalCode = null;
    this.places = null;
  }

  public ZipCode(String postalCode, Set<Places> places) {
    this.postalCode = postalCode;
    this.places = places;
  }

  @lombok.Value
  private static class Places {
    @JsonAlias("state abbreviation")
    private  final String stateCode;
  }
}

我以为如果我用

ZipCode zip = getZipObject();
String stateCode = zip.getPlaces().stream().findFirst().toString();

我可以得到 stateCode 作为字符串。在我的示例中,stateCode 应该是 "CA"。相反,我得到 Optional[ZipCode.Places(stateCode=NY)]。如果有人可以帮助我,我将不胜感激。我将邮政编码 class 保存在单独的 class 中。我想保持这种状态。我所举的大部分例子。 using stream 倾向于使用集合对象本身。我想避免让我的 Places 对象可公开访问。

我能够像这样通过修改 ZipCode class 获得 stateCode 属性

@lombok.Value
public class ZipCode {
  @JsonAlias("post code")
  private final String postalCode;
  private final  Set<Places> places;

  @lombok.Value
  public static class Places {
    @JsonAlias("state abbreviation")
    private  final String stateCode;
  }
}

然后我就这样使用流

if(zip.getPlaces().stream().findFirst().isPresent())
     String state = zip.getPlaces().stream().findFirst().get().getStateCode();

这会为示例 json 生成 "CA" 的输出。希望这对某人有所帮助。