在构建Json数组时,最后一个对象出现在数组中

时间:2017-05-29 16:53:01

标签: json groovy

我正在调用一个宁静的服务来将数据库中的文档作为JSON字符串获取。所以当我做以下工作时,我有两个循环foaList, otaList 一个循环我得到了正确的JSON响应:

此代码检索正确的响应:

def param = new HashMap();
    builder{
        results foaList.collect{
            [
              result:   [   
                                         //Here I have not added all json keys and vlaues as in the second case.
                          name: it.getFlexiObject().getByString("name"),
                          version: it.getFlexiObject().getByString("version"),
                      author: it.getFlexiObject().getByString("author")
                 ] 
            ]
        }       
    }

带有一个foaList循环的Json String:

{
    "results": [
        {
            "result": {
                "name": "Benzin consume",
                "version": "09.55.00",
                "author": "Alex"
            }
        },
        {
            "result": {
                "name": "Jaspersoft Ultimate guide",
                "version": "sdfdsv",
                "author": "sdvdsv"
            }
        }
    ]
}

但是当我尝试遍历这两个列表时,我得到了具有相同对象的JSON String。

def param = new HashMap();
    builder{
        results foaList.collect{
            otaList.eachWithIndex{item, index ->
               param.put(item.getName(), it.getFlexiObject().getByString(item.getName()));
               }
               result:param       
        }       
    }

循环遍历两个循环之后的Json String:

{
    "results": [
        {
            "content": "",
            "author": "Alex",
            "description": "Test Json",
            "link": "21120",
            "name": "Benzin consume",
            "fileName": "",
            "contentType": "",
            "version": "09.55.00"
        },
        {
            "content": "",
            "author": "Alex",
            "description": "Test Json",
            "link": "21120",
            "name": "Benzin consume",
            "fileName": "",
            "contentType": "",
            "version": "09.55.00"
        }
    ]
}

如何在迭代两个列表foaList, otaList时获取带有两个对象的JSON字符串?

1 个答案:

答案 0 :(得分:0)

问题是我的param地图在第一个循环之外:

def param = new HashMap();
    builder{
        results foaList.collect{
            def param = new HashMap();
            otaList.eachWithIndex{item, index ->
               param.put(item.getName(),    it.getFlexiObject().getByString(item.getName()));
               }
        }

    }

但它应该是:

builder{
    results foaList.collect{
        def param = new HashMap();
        otaList.eachWithIndex{item, index ->
           param.put(item.getName(), it.getFlexiObject().getByString(item.getName()));
           }

    }

}