2017-05-29 108 views
0

我正在调用一个restful服务来获取服务器上的可用文档,其中获取JSON作为响应。我建立了JSON字符串与JSONBuilder所以调用此链接构建JSON字符串时迭代两个循环

http://localhost:8080/httpConnector/Rest/Documents?Accept=application/json

我得到下面的JSON字符串时:

{ 
    "results": [ 
     { 
      "result": { 
       "name": "Test traisy", 
       "version": "sdvdsv", 
       "author": "sdvdsv" 
      } 
     }, 
     { 
      "result": { 
       "name": "Jaspersoft Ultimate guide", 
       "version": "sdfdsv", 
       "author": "sdvdsv" 
      } 
     }, 
     { 
      "result": { 
       "name": "Dohrn", 
       "version": "12.19.00", 
       "author": "sdfdsf" 
      } 
     } 

    ] 
} 

代码

String accept = getValue("Accept"); 
accept = "application/xml";     
if ("application/xml".equals(accept)){ 
    builder=new groovy.xml.MarkupBuilder(writer); 
}else{ 
    builder=new groovy.json.JsonBuilder(); 
} 

    builder{ 
    results foaList.collect{ 
     [ 
        //Here I want to loop through the otaList to do something like that "ota.getName(), foa.getFlexiObject().getByString(ota.getName())" 
      result: [ 
        name: it.getFlexiObject().getByString("name"), 
       version: it.getFlexiObject().getByString("version"), 
       author: it.getFlexiObject().getByString("author") 
       ] 
     ] 
    } 

} 

现在我想以编程方式添加属性。因此,我不得不遍历otaList做类似的东西

builder.'results'() { 
    for(FlexiObjectAttachment foa: foaList){ 
     for(ObjectTypeAttribute ota : otaList){ 
      param.put(ota.getName(), foa.getFlexiObject().getByString(ota.getName())); 

     } 
     result(param); 
    }  
} 

这个版本只适用于在XML生存。

回答

0

您可以尝试的是直接在collect调用中执行foaota的组合。 这样,您最初创建的字典将具有正确的结构。

喜欢的东西下面的例子中

def foaList = [1, 2, 3, 4] 
def otaList = ['A', 'B', 'C'] 

foaList.collect { foa -> 
    result = [name: "Name$foa", version: "v$foa", author: "Author$foa"] 
    otaList.each { ota -> result[ota] = "$ota$foa" } 
    [ result: result ] 
}