【问题标题】:How to get values from a list that has child lists and store all the values in order in another list如何从具有子列表的列表中获取值并将所有值按顺序存储在另一个列表中
【发布时间】:2014-02-19 07:57:07
【问题描述】:

我有一个名为 ionList 的列表,其中包含名为 structs 的值。 列表中的每个结构都有更多的列表,并且这些列表中还有更多的结构。你可以把它想象成一种父列表和子列表

我想完全检索 ionList 中的所有结构并将其存储在一个名为 StructList 的列表中。

我使用的代码是递归代码,但是当我在 ionList 中遇到子列表时调用递归函数时,数据会丢失。

    public List<IonStruct> findStructsFromParentList(IonList ionList) {
        String objectType = "object_type";
        String diffType = "diff_type";
        String childList = "children";
        IonList ionChildList = null;
        IonList ionChildList1 = null;
        List<IonStruct> ionStructList = new ArrayList<IonStruct>();
        System.out.println("ION LIST"+ionList.size());
        for (int index = 0; index < ionList.size();index++) {
            ionStructList.add((IonStruct) ionList.get(index));
            ionChildList = (IonList) ionStructList.get(index).get(childList);
            if (ionChildList != null) {
                System.out.println("Found child");
                ionStructList.addAll(findStructsFromParentList(ionChildList));

            }

        }

        return ionStructList;


    }

发现的 childList 在我的递归调用中改变了我的 for 循环初始化,我认为这是不解析多个包含子列表的结构的原因。请帮帮我..

【问题讨论】:

  • 我只是盯着这个问题,不久前你问了一个更长的版本。突然你把它删了,我无法回答! :-(
  • 使用调试器查看是否对所有列表项执行了 for 循环。我觉得findStructsFromParentList(ionChildList)方法中可能会抛出一些异常
  • 我也取消删除了那个帖子...我觉得它很混乱所以删除了它
  • 哈,是的,这有点令人困惑。但请忽略我之前的评论;我只是在逗你。

标签: java json list recursion


【解决方案1】:

上面写着的那一行

ionChildList = (IonList) ionStructList.get(index).get(childList);

应该说

ionChildList = (IonList)((IonStruct) ionList.get(index)).get(childList);

因为在ionStructList 内,索引会有所不同,因此使用您的代码,您将无法检索到正确的列表。

【讨论】:

    猜你喜欢
    • 2022-07-31
    • 2022-01-05
    • 2020-12-04
    • 2014-03-24
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多