如何使用泛型函数解析json?

问题描述 投票:2回答:1

我想编写一个泛型函数来解析一个json字符串(代码中的stringEtcdContent)。该字符串包含一个键值为“value”的对象列表。我将json解析为一个树,获取一个JsonNode的列表(下面的valueNodes),其中包含要使用泛型类解析的字符串。我有这个函数的类是这样的:“public abstract class DashboardReportProvider”。根据这里的类似问题,我写了这个函数:

  @SuppressWarnings("unchecked")
  public List<T> getStatusList(String path) {
    Class<T> clazz;
    clazz = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    List<T> statusList = new ArrayList<>();
    T statusItem;
    ObjectMapper mapper = new ObjectMapper();
    try {
      String stringEtcdContent = etcdCommandExecutor.getEtcdValue(path);
      JsonParser parser=new MappingJsonFactory().createParser(stringEtcdContent);
      JsonNode rootNode=parser.readValueAsTree();
      List<JsonNode> valueNodes=rootNode.findValues("value");
      Iterator<JsonNode> valueNodesIterator=valueNodes.listIterator();
      while (valueNodesIterator.hasNext()) {
        JsonNode valueNode=(JsonNode)valueNodesIterator.next();
        ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
        String valueString = writer.writeValueAsString(valueNode);
        statusItem = mapper.readValue(valueString, clazz);
        statusList.add(statusItem);
      }
      return statusList;
    } catch (Exception e) {
      LOG.error(e.getMessage());
    }
    return statusList;
  }

它编译得很好,但是当我尝试运行代码时,我得到了这个错误:“[ERROR] java.lang.Class无法转换为java.lang.reflect.ParameterizedType”。怎么了?

java
1个回答
0
投票

试试ObjectMapper,

new ObjectMapper().readValue(path,Object.class);

其中Object.class - 强制转换为类型

© www.soinside.com 2019 - 2024. All rights reserved.