【问题标题】:Filter pojo properties by some pattern按某种模式过滤 pojo 属性
【发布时间】:2018-10-08 17:36:29
【问题描述】:

我已经将一些服务器响应(很长的响应)转换为 POJO(通过使用 moshi 库)。

最终我得到了“项目”列表,每个“项目”如下所示:

public class Item
{
    private String aa;
    private String b;
    private String abc;
    private String ad;
    private String dd;
    private String qw;
    private String arew;
    private String tt;
    private String asd;
    private String aut;
    private String id;
    ...
}

我真正需要的是提取所有以 "a" 开头的属性,然后我需要将它们的值用于进一步的 req ...

有什么方法可以在没有反射的情况下实现它? (可能使用流?)

谢谢

【问题讨论】:

  • 您需要注释或某些类型的反射(尽管可以隐藏在其他工具下)。既然你所有的值都是字符串,有什么理由不忘记 pojo 并将它们放入 HashMap 中?然后它们可以很容易地被操纵。反射是一种对自己进行“反射”并查看变量名称等的能力——因此根据定义,没有它,您将无法处理变量名称。
  • 谢谢,将尝试使用 JSONObject / Gson 方向

标签: java json properties filtering moshi


【解决方案1】:

使用 guava-functions 转换,您可以使用以下方法转换您的项目:

 public static void main(String[] args) {
        List<Item> items //
        Function<Item, Map<String, Object>> transformer = new Function<Item, Map<String, Object>>() {
            @Override
            public  Map<String, Object> apply(Item input) {
                  Map<String, Object> result  = new HashMap<String, Object>();
            for (Field f : input.getClass().getDeclaredFields()) {
                if(! f.getName().startsWith("a")) {
                    continue;
                }
                Object value = null;
                try {
                    value = f.get(input);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("failed to cast" + e)
                }
                result.put(f.getName(), value);
               }

            return result
        };
        Collection<Map<String, Object> result
                = Collections2.transform(items, transformer);
    }

【讨论】:

    【解决方案2】:

    听起来您可能希望对常规 Java 映射结构执行过滤。

    // Dependencies.
    Moshi moshi = new Moshi.Builder().build();
    JsonAdapter<Map<String, String>> itemAdapter =
        moshi.adapter(Types.newParameterizedType(Map.class, String.class, String.class));
    String json = "{\"aa\":\"value1\",\"b\":\"value2\",\"abc\":\"value3\"}";
    
    // Usage.
    Map<String, String> value = itemAdapter.fromJson(json);
    Map<String, String> filtered = value.entrySet().stream().filter(
        stringStringEntry -> stringStringEntry.getKey().charAt(0) == 'a')
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    

    您可以将过滤逻辑封装在自定义 JsonAdapter 中,但验证和业务逻辑往往会很好地留给应用程序使用层。

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 1970-01-01
      • 2019-08-23
      • 2017-05-05
      • 1970-01-01
      • 2020-08-03
      相关资源
      最近更新 更多