我有一个像这样的对象图:

root
    : childs (array)
        : childs (array)


我正在以此构建一个JSON响应,因此我需要遍历每个集合以创建如下代码:

// code for root

// loop through direct root childs
for (Child child : childs) {

    // Loop through the childs of the object in current context.
    for (AnotherChild anotherChild : moreChilds) {

    }
}


您如何避免这样的代码?最终将是一个箭头。我可以为每个级别的for循环创建自己的方法,但这是一个好方法吗?还有其他更好的方法吗?

最佳答案

如果我们正在谈论这个特定问题(构建JSON响应),则可以使用jackson之类的序列化程序或编写自定义序列化程序。关于此主题有一个相关问题https://stackoverflow.com/questions/338586/a-better-java-json-library

另一方面,对于其他一些用途,您可以使用更实用的方法,例如GuavaLambdaj

但是,当涉及到大的O复杂性时,这些对您没有太大帮助,因此,如果可能的话,您可能想尝试其他方法。

10-04 10:09