json—在有多个id值时解析jsonobject以访问id(java)

x33g5p2x  于 2021-07-06  发布在  Java
关注(0)|答案(3)|浏览(399)

我从一个api获得了一个json响应,该api提供了一个json格式的调用记录列表。我想解析数据并找到记录id,我的问题是每个json记录都有多个id,我不知道如何访问正确的id。请记住,在运行请求之前,我不知道id的值是“34614870007335176”。
这是我接收json的代码,我创建了一个jsonobject,这样我就可以很有希望地存储值。
1.

Response response = client.newCall(request).execute();
            String responseBody = response.body().string();
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            JsonParser parser = new JsonParser();
            JsonElement je = parser.parse(responseBody);
            String prettyJsonString = gson.toJson(je);

            JSONObject json = new JSONObject(prettyJsonString);
            System.out.println("Json = " + json);

我需要访问的json id旁边有一条注解:

"data": [
    {
      "Owner": {
        "name": "My namen",
        "id": "346148700000017",
        "email": "m@gmail.com"
      },
      "$state": "save",
      "$process_flow": false,
      "Street": "95## ### ######",
      "id": "**3461487000073355176**", ----This is the ID I need -----
      "Coverage_A_Dwelling": 100000,
      "$approval": {
        "delegate": false,
        "approve": false,
        "reject": false,
        "resubmit": false
      },
      "Created_Time": "2020-12-10T09:05:17-05:00",
      "Property_Details": "Primary Residence",
      "Created_By": {
        "name": "My name",
        "id": "346148700000017",
        "email": "m@gmail.com"
      },
      "Description": "Created on Jangl: https://jan.gl/crwp773ytg8",
      "$review_process": {
        "approve": false,
        "reject": false,
        "resubmit": false
      },
      "Property_State": "FL",
      "Property_Street": "95",
      "Roof_Material": "Asphalt Shingle",
      "Full_Name": "Clare Em",
      "Property_City": "Land ",
      "Email_Opt_Out": false,
      "Lead_I_D": "4FFEC0C5-FBA1-2463-DB9B-C38",
      "Insured_1_DOB": "1942-02-20",
      "$orchestration": false,
      "Tag": [],
      "Email": "cr@yahoo.com",
      "$currency_symbol": "$",
      "$converted": false,
      "Zip_Code": "338",
      "$approved": true,
      "$editable": true,
      "City": "Land O Lakes",
      "State": "FL",
      "Structure_Type": "Single Family",
      "Prior_Carrier": {
        "name": "Default Carrier (DO NOT DELETE OR CHANGE)",
        "id": "3461487000000235093"
      },
      "Source": {
        "name": "EverQ",
        "id": "346148700006474"
      },
      "First_Name": "Clarence",
      "Modified_By": {
        "name": "My name",
        "id": "3461487000000172021",
        "email": "m@gmail.com"
      },
      "Phone": "7036159075",
      "Modified_Time": "2020-12-10T09:05:17-05:00",
      "$converted_detail": {},
      "Last_Name": "####",
      "$in_merge": false,
      "$approval_state": "approved",
      "Property_Zip": "34638"
    }
  ],
  "info": {
    "per_page": 200,
    "count": 1,
    "page": 1,
    "more_records": false
  }
}
pvcm50d1

pvcm50d11#

发布的json响应缺少初始的“{”。
您的json包含 data ,这是一个 JSONArrayOwner 物体。为了得到 id 第一个所有者的字段(数组元素0):

// existing code
JSONObject json = new JSONObject(prettyJsonString);
System.out.println("Json = " + json);

// get the id field
JSONArray dataArray = (JSONArray)json.get("data");
JSONObject data0 = (JSONObject) dataArray.get(0);
JSONObject owner = (JSONObject) data0.get("Owner");
String id = owner.getString("id");
System.out.println(id);
ioekq8ef

ioekq8ef2#

如果我理解正确,你可以得到如下id:
在这里, json 具有以下值。

[
{
  "Owner": {
    "name": "My namen",
    "id": "346148700000017",
    "email": "m@gmail.com"
  }, 
"id": "**3461487000073355176**"
...
}
]

现在我可以迭代jsonarray来获取id。

JSONArray jsonArray = new JSONArray(json);
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = (JSONObject) jsonArray.get(i);
        String id = (String) jsonObject.get("id");
        System.out.println(id);
    }

打印出来 **3461487000073355176** .
你能做到的 jsonObject.getJSONArray("data"); 在您的示例中获取json数组。

zlwx9yxi

zlwx9yxi3#

不确定是否理解正确,但如果您需要获得该“级别”中的所有ID,为什么不尝试将其建模为一个类,而不是使用解析器,并让gson进行解析(如果您需要添加更多详细信息,这个类可能会很有用)?
例如,定义如下:

@Getter @Setter
// This models the response string from body
public class Response {
    @Getter @Setter
    // This models objects in the data list/array
    public static class IdHolder {
        // Only id because not interested of the rest
        private String id;
    }
    // Only list of id holders because not interested of the rest
    private List<IdHolder> data;
}

那么就很简单了:

Response res = gson.fromJson(responseBody, Response.class);
// Print out what you got
res.getData().stream().map(IdHolder::getId).forEach(System.out::println);

相关问题