从json对象提取特定数据并将其存储在列表中

时间:2020-09-16 10:52:03

标签: java json groovy devops bitbucket-api

我是json格式领域的新手。我将Json信息存储在json对象中,我只想提取列表中的名称键值。至少我有一个用户,有时不止一个用户。使用Java或Groovy提取。

{
  "reviewers": [
    {
      "user": {
        "name": "name1.n1",
        "emailAddress": "example@example.com"
      },
      "role": "REVIEWER"
    },
    {
      "user": {
        "name": "name2.n2",
        "emailAddress": "example2@example.com"
      },
      "role": "REVIEWER"
    }
  ]
}

3 个答案:

答案 0 :(得分:2)

此处的基本groovy + json文档:https://groovy-lang.org/json.html

import groovy.json.JsonSlurper

def json = '''{
  "reviewers": [
    {
      "user": {
        "name": "name1.n1",
        "emailAddress": "example@example.com"
      },
      "role": "REVIEWER"
    },
    {
      "user": {
        "name": "name2.n2",
        "emailAddress": "example2@example.com"
      },
      "role": "REVIEWER"
    }
  ]
}
'''

def obj = new JsonSlurper().parseText(json)

println obj.reviewers.collect{ it.user.name } // v1
println obj.reviewers*.user.name              // the same as above but shorter

答案 1 :(得分:0)

将Java与库org.json.JSONObject一起使用;

   JSONObject json =new JSONObject(YOUR_JSON_HERE );        
            JSONArray array = json.getJSONArray("reviewers" );
            for(int i=0;i<array.length();i++){
                JSONObject user =array.getJSONObject(i);   
                System.out.println(user.getJSONObject("user").get("name"));
            }
            
    
        }

答案 2 :(得分:0)

您可以仅使用Groovy来获得这样的名称列表:

jason = '''{
  "reviewers": [
    {
      "user": {
        "name": "name1.n1",
        "emailAddress": "example@example.com"
      },
      "role": "REVIEWER"
    },
    {
      "user": {
        "name": "name2.n2",
        "emailAddress": "example2@example.com"
      },
      "role": "REVIEWER"
    }
  ]
}
'''


import groovy.json.JsonSlurper

def jsonslurper = new JsonSlurper()
def object = jsonslurper.parseText(jason)

List names = object.findAll { it.value instanceof List }
    .values()
    .flatten()
    .collect { it.user.name }

println names