0

我有一些服务器响应(很长),我已经转换为 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 ...

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

谢谢

4

2 回答 2

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);
    }
于 2018-04-27T20:32:32.743 回答
0

听起来您可能希望在常规 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 中,但验证和业务逻辑往往会很好地留给应用程序使用层。

于 2018-04-30T07:35:38.430 回答