从嵌套的Java对象获取字段的所有值

时间:2018-09-20 09:27:07

标签: java reflection java-8

我有一个Java对象,如下所示。我需要遍历此嵌套对象并获取一个字段的所有值。下面的Java对象的“时间”。

如果是列表,则可以使用Java 8过滤器。但是如何在对象上执行此操作?

此外,我需要以一种通用的方式来做。

    {
  "dataType": "Node",
  "totalCount": 1,
  "count": 1,
  "startIndex": 0,
  "data": [
    {
      "id": "a4b7a825f67930965747445709011120-Node-6f638b5e71debd5807ec7fb73b9dc20b",
      "refObjects": {},
      "tid": "a4b7a825f67930965747445709011120",
      "creationDate": "2018-09-20T06:55:36.742+0000",
      "lmd": "2018-09-20T06:55:36.799+0000",
      "exceptions": [
        {
          "name": "projectedInventory",
          "status": "Stockout",
          "severity": "High",
          "time": "2018-09-20T00:00:00.000+0000"
        }
      ],
      "criticalities": [
        "HotItem"
      ],
      "customerName": "Best Buys",
      "supplierName": "Samsung",
      "customerItemName": "Ship to item name",
      "nodeType": "inventory",
      "supplierItemName": "Ship from item name",
      "shipToSiteName": "IT06",
      "shipFromSiteName": "IT07",
      "status": "Active",
      "lob": "HC",
      "processType": "demandSupply",
      "measures": {
        "maxInventory": [
          {
            "refObjects": {},
            "time": "2018-09-26T00:00:00.000+0000",
            "quantity": 0
          },
          {
            "refObjects": {},
            "time": "2018-09-27T00:00:00.000+0000",
            "quantity": 0
          }
        ],
        "maxDistribution": [
          {
            "refObjects": {},
            "time": "2018-09-28T00:00:00.000+0000",
            "quantity": 0
          },
          {
            "refObjects": {},
            "time": "2018-09-29T00:00:00.000+0000",
            "quantity": 0
          },
          {
            "refObjects": {},
            "time": "2018-09-30T00:00:00.000+0000",
            "quantity": 0
          },
          {
            "refObjects": {},
            "time": "2018-10-07T00:00:00.000+0000",
            "quantity": 0
          },
          {
            "refObjects": {},
            "time": "2018-10-14T00:00:00.000+0000",
            "quantity": 0
          },
          {
            "refObjects": {},
            "time": "2018-10-21T00:00:00.000+0000",
            "quantity": 0
          },
          {
            "refObjects": {},
            "time": "2018-10-28T00:00:00.000+0000",
            "quantity": 0
          },
          {
            "refObjects": {},
            "time": "2018-11-04T00:00:00.000+0000",
            "quantity": 0
          },
          {
            "refObjects": {},
            "time": "2018-11-25T00:00:00.000+0000",
            "quantity": 0
          }
        ]
      },
      "customerItemDescription": "EXP08CN1W6  PORTABLE AIR CONDITIONER HC",
      "materialGroup": "ELX",
      "shipToSiteDescription": "IT - BE10 Porcia Hub"
    }
  ],
  "typeCounts": null
}

现在,我想检索“时间”字段的所有值并将其保存在列表中。最好的方法是什么?

输出应该是这样的:

{
  "time": [
    "2018-12-30T00:00:00.000+0000",
    "2018-08-24T12:00:00.000+0000"
  ]
}

2 个答案:

答案 0 :(得分:0)

您也可以使用反射,但是apache-commons使其更容易。我在下面编写的方法有两个参数,一个是您的POJO对象,另一个是空列表。即使您输入的是嵌套的,它也会通过填充输入对象中属性"time"的所有值来返回相同的列表宾语。在else if中,我添加了一个条件,用于检查className是否包含“ com.your.packageName”,这是因为在这里,我假设所有POJO(可以嵌套在输入对象中)存储在包“ com.your.packageName”中,因此,如果将所有POJO存储在一个位置,则将其替换为包名。 为common-beanutills添加以下依赖项。

 <groupId>commons-beanutils</groupId>
 <artifactId>commons-beanutils</artifactId>
 <version>1.9.2</version>

    import org.apache.commons.beanutils.BeanMap;
    import org.apache.commons.beanutils.PropertyUtilsBean;

     private static List<String> getPropertyValue(Object myObj, List<String> timeList) {
            final BeanMap beanMap = new BeanMap(myObj);
            PropertyUtilsBean pp = new PropertyUtilsBean();
            beanMap.keySet().stream().forEach(x -> {
                try {
                     String propertyName= ""+x;
                     //GET THE CLASS TYPE OF PROPERTY
                     String proprtyTypeClassName=""+pp.getPropertyType((Object)myObj,propertyName);
                     System.out.println(propertyName+"  "+proprtyTypeClassName);
                     if(propertyName.equals("time")) {
                         //GET THE VALUE OF A propertyName FROM object myObj
                         timeList.add((String)pp.getProperty(myObj, propertyName));
                     }
                     else if(proprtyTypeClassName.contains("com.your.packageName")) {
//recursively call same method if value is another POJO object nested inside
                         getPropertyValue(pp.getProperty(myObj, propertyName),timeList);
                     }
                } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                    e.printStackTrace();
                }
            });
            return timeList;
        }

如果您有任何疑问,请告诉我。

答案 1 :(得分:0)

非常感谢。我正在尝试一些解决方案,并在下面找到了一个。让我知道这看起来是否正确:

package com.company.dct.exec.lib.relationships.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.JsonPath;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component("objectPathValuesExtractor")
public class ObjectPathValuesExtractor {
    private static final Logger LOGGER = LoggerFactory.getLogger(ObjectPathValuesExtractor.class);

    /**
     * Extract values for a given path from current object.
     *
     * @param object the object
     */

    public <T extends Object> T extractValues(Object object, String pathExpression) {
        T values = null;
        if (object == null) {
            return values;
        }
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.setDefaultPropertyInclusion(JsonInclude.Value.construct(JsonInclude.Include.ALWAYS, JsonInclude.Include.NON_NULL));
            Map<String, Object> mappedObject = mapper.convertValue(object, Map.class);
            values = JsonPath.read(mappedObject, pathExpression);
        } catch (Exception e) {
            LOGGER.error("Failed to load alert referenced object.", e);
        }
        return values;
    }
}

我在这里使用
compile group: 'com.jayway.jsonpath', name: 'json-path', version: '2.4.0' 来自apache

然后我调用此函数

List<Map<String, Extensible>> refObjects = objectPathValuesExtractor.extractValues(object, "$..time");