简体   繁体   English

Map 字符串 arraylist 获取键和值

[英]Map string arraylist getting key and value

From the API response, I'm parsing the JSON从 API 响应中,我正在解析 JSON

String myData = jsonSlurper.parseText(responseBody)
Map parsedBiblio = jsonSlurper.parseText(myData)

below is the output of parsedBiblio下面是parsedBiblio的output

{"Data": {"AppNumber": "15671037", "CustomerNumber": "81744", "Date": "08-07-2017", "Status": "Active"}, 

 "Applicants": [{"Name": "abcd Inc.", "Address": "xxx, CA (US)"}],

below is the code of retrieving the Data key and corresponding value下面是检索Data键和对应值的代码

Map<Object, Object> innerMap = parsedBiblio.get("Data")
for (Object objectName : innerMap.keySet()) {
   
       println("Key: " + objectName + " Value: "+ innerMap.get(objectName) +".");
 }

Let me know how I can retrieve the Applicants key and the corresponding values, because this is map<string,List<string> format, so I will declare the innermap in the below format让我知道如何检索Applicants者键和相应的值,因为这是map<string,List<string>格式,所以我将按以下格式声明内部映射

Map<String, List<String>> innerMapApplicant = parsedBiblio.get("Applicants")

I get this error我收到这个错误

Cannot cast object '[{Address=xxx, CA (US), Name=abcd Inc.}]' with class 'java.util.ArrayList' to class 'java.util.Map' due to: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.util.Map(groovy.json.internal.LazyMap) Cannot cast object '[{Address=xxx, CA (US), Name=abcd Inc.}]' with class 'java.util.ArrayList' to class 'java.util.Map' due to: groovy.lang.GroovyRuntimeException:找不到匹配的构造函数:java.util.Map(groovy.json.internal.LazyMap)

I think you should try retrieving Applicant as follow:我认为您应该尝试按以下方式检索申请人:

List<Map<String,String>> applicantList =  = parsedBiblio.get("Applicants")

You can fetch key and value in the map as follow:您可以在 map 中获取键和值,如下所示:

  for(Map<String,String> applicantMap: applicantList)
  {
       for (Object objectName : applicantMap.keySet()) 
       {
          println("Key: " + objectName + " Value: "+ applicantMap.get(objectName) +".");
       }
   }

Don't understand why you double parse a String不明白为什么要双重解析字符串

If responseBody is an string, you can write:如果 responseBody 是一个字符串,你可以这样写:

def json = jsonSlurper.parseText(responseBody)
println json.Data.Applicants.Name
println json.Data.Applicants.Address

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM