如何仅使用GSON和Java访问JSON数组的嵌套元素

如何仅使用GSON和Java访问JSON数组的嵌套元素,java,arrays,json,nested,gson,Java,Arrays,Json,Nested,Gson,我无法使用org.json包 问题 使用httpget方法从患者病历数据库中检索信息。查询https://jsonmock.hackerrank.com/api/medical_records查找所有记录。查询结果是分页的,可以通过在查询字符串?&page=num后面追加num来进一步访问,其中num是页码 API的查询响应是一个JSON,包含以下五个字段: page: the current page per_page: the maximum number of results per pa

我无法使用
org.json包

问题 使用
httpget
方法从患者病历数据库中检索信息。查询<代码>https://jsonmock.hackerrank.com/api/medical_records查找所有记录。查询结果是分页的,可以通过在查询字符串
?&page=num
后面追加
num
来进一步访问,其中
num
是页码

API的查询响应是一个JSON,包含以下五个字段:

page: the current page
per_page: the maximum number of results per page
total: the total number of records in the search result
total_pages: the total number of pages which must be queried to get all the results
data: an array of JSON objects that contain medical records
响应中的数据字段包含具有以下架构的病历列表:

  • id
    :记录的唯一id
  • 时间戳
    :记录生成时的时间戳(UTC为毫秒)
  • userId
    :记录交易的用户的id
  • userName
    :记录交易的患者/用户的姓名
  • userDob
    :格式为DD-MM-YYYY的用户出生日期
  • vitals
    :对象,用户的vitals
  • vitals.bloodPressureDiastole
    :用户的舒张压读数,毫米汞柱
  • vitals.bloodPressureSystole
    :用户的收缩压读数,毫米汞柱
  • vitals.pulse
    :用户的脉搏频率,每分钟跳动数
  • vitals.breatsingrate
    :用户的呼吸频率,每分钟呼吸次数
  • vitals.体温
    :用户的体温,华氏度
  • diagnosis.id
    :诊断的id
  • diagnosis.name
    :诊断的条件的名称
  • 诊断。严重性
    :诊断条件的严重性
  • 医生
    :对象,诊断该疾病的医生
  • doctor.id
    :诊断该疾病的医生的id
  • doctor.name
    :诊断该疾病的医生的姓名
  • meta
    :对象,用户的元信息
  • meta.height
    :用户的当前高度,厘米
  • meta.weight
    :用户的当前重量,磅
获取所有医疗记录并根据以下条件进行筛选:

ageStart ≤ the age of the user at the time of the record creation timestamp ≤ ageEnd
对于符合第一个
标准的用户,请选择血压力数据表-血压力数据表>bpDiff

功能描述

Complete the function getRecordsByAgeGroup in the editor below.

getRecordsByAgeGroup has the following parameter(s):

int ageStart: the minimum age requirement (inclusive)

int ageEnd: the maximum age requirement (inclusive)

int bpDiff: the difference in systolic and diastolic pressures must be less than this value
返回:
int[]
:符合上述条件的记录ID的排序数组。如果没有匹配的记录,则返回[-1]

限制条件:

0 ≤ ageStart, ageEnd, bpDiff ≤ 102
我的代码

    import java.net.*;
import com.google.gson.*;

class Result {

    /*
     * Complete the 'getRecordsByAgeGroup' function below.
     *
     * The function is expected to return an INTEGER_ARRAY.
     * The function accepts following parameters:
     *  1. INTEGER ageStart
     *  2. INTEGER ageEnd
     *  3. INTEGER bpDiff
     *
     *  https://jsonmock.hackerrank.com/api/medical_records

     */

    public static List<Integer> getRecordsByAgeGroup(int ageStart, int ageEnd, int bpDiff) {
        int startPage = 1;
        int totalPages = 10;
        String response;
        ArrayList<Integer> ids = new ArrayList<>();
        ArrayList<Long> times = new ArrayList<>();
        List<String> dobs = new ArrayList<>();
        ArrayList<Integer> bpd = new ArrayList<>();
        ArrayList<Integer> bps = new ArrayList<>();
        ArrayList<Integer> results = new ArrayList<>();

        while (startPage <= totalPages) {
            try{
                URL obj = new URL ("https://jsonmock.hackerrank.com/api/medical_records?&page=" + startPage);
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                con.setRequestMethod("GET");
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                while ((response = in.readLine()) != null) {
                    JsonObject convertedObject = new Gson().fromJson(response, JsonObject.class);
                    totalPages = convertedObject.get("total_pages").getAsInt();
                    JsonArray data = convertedObject.getAsJsonArray("data");

                    for (int i = 0; i < data.size(); i++){
                        System.out.println(data.get(i));
                        int id = data.get(i).getAsJsonObject().get("id").getAsInt();
                        ids.add(id);
                        Long ts = data.get(i).getAsJsonObject().get("timestamp").getAsLong();
                        times.add(ts);
                        String birth = data.get(i).getAsJsonObject().get("userDob").getAsString();
                        dobs.add(birth);


import java.net.*;
导入com.google.gson.*;
班级成绩{
/*
*完成下面的“GetRecordsByegroup”函数。
*
*该函数应返回一个整数数组。
*该函数接受以下参数:
*1.整数ageStart
*2.整数AGEND
*3.整数bpDiff
*
*  https://jsonmock.hackerrank.com/api/medical_records
*/
公共静态列表getRecordsByAgeGroup(int-ageStart、int-ageEnd、int-bpDiff){
int起始页=1;
int totalPages=10;
字符串响应;
ArrayList ID=新的ArrayList();
ArrayList时间=新建ArrayList();
List dobs=new ArrayList();
ArrayList bpd=新的ArrayList();
ArrayList bps=新的ArrayList();
ArrayList结果=新建ArrayList();
while(开始页面ageStart)和(userage==ageEnd | | userage bpDiff){
添加(id.get(i));
}
}
}捕获(例外情况除外){
例如printStackTrace();
}
}
返回结果;
}
公共静态int calculateAgeWithJava7(
生日,
日期(当前日期){
DateFormat格式化程序=新的SimpleDateFormat(“dd-MM-yyyy”);
intd1=Integer.parseInt(formatter.format(birthDate));
intd2=Integer.parseInt(formatter.format(currentDate));
整数年龄=(d2-d1)/10000;
回归年龄;
}
}

当JSON已经被解析时,不知道为什么您认为需要一个新的
JsonParser

为了让我们都能看到您正在解析的内容,这里是其中的一部分:

{
“页码”:1,
“每页”:10,
“总数”:99,
“总页数”:10页,
“数据”:[
{
“id”:1,
“时间戳”:1565637002408,
“诊断”:{
“id”:3,
“名称”:“肺栓塞”,
“严重程度”:4
},
“重要事项”:{
“血压指数”:154,
“血压调节器”:91,
“脉搏”:125,
“忘恩负义者”:32,
“体温”:100
},
“医生”:{
“id”:2,
“姓名”:“阿诺德·布洛克博士”
},
“用户ID”:2,
“用户名”:“鲍勃·马丁”,
“userDob”:“14-09-1989”,
“元”:{
“高度”:174,
“重量”:172
}
},
...
]
}
Java是一种面向对象的语言。用它!创建一个用于存储数据值的类,然后创建一个
列表

其中,
数据
类为:

public class Data {
    private int id;
    private long timestamp;
    private String birthDate;
    private int bpDiastole;
    private int bpSystole;

    // Getters and setter here
}

将返回您需要的JsonObject。您只需通过for循环(.get(i))遍历数组

什么是
答案
?对不起)是您的Json字符串。{“页面”:“1”,“每页”:10,“总计”:99,“总计”:10,“数据”:[{“id”:1,“时间戳”:1565637002408,…..从该URL检索到的Json字符串是
response
变量中的字符串,并且已经被解析为
convertedObject
变量,那么为什么它会突然被命名为
answer
,为什么我们要再次解析它?---建议您重新查看问题中的代码问题是how-to-access-nested-elements-of-a-json-array-using-only-gson-with-java。我只是演示如何做。可以使用的参数是opti
List<Data> dataList = new ArrayList<>();
JsonArray dataArray = convertedObject.getAsJsonArray("data");
for (JsonElement dataElem : dataArray) {
    System.out.println(dataElem);

    JsonObject dataObj = dataElem.getAsJsonObject();
    int id = dataObj.get("id").getAsInt();
    long timestamp = dataObj.get("timestamp").getAsLong();
    String userDob = dataObj.get("userDob").getAsString();

    // Now for the good stuff
    JsonObject vitals = dataObj.getAsJsonObject("vitals");
    int bpDiastole = vitals.get("bloodPressureDiastole").getAsInt();
    int bpSystole = vitals.get("bloodPressureSystole").getAsInt();

    Data data = new Data();
    data.setId(id);
    data.setTimestamp(timestamp);
    data.setBirthDate(userDob);
    data.setBpd(bpDiastole);
    data.setBps(bpSystole);
    dataList.add(data);
}
public class Data {
    private int id;
    private long timestamp;
    private String birthDate;
    private int bpDiastole;
    private int bpSystole;

    // Getters and setter here
}
    JsonObject jsonObject = gson.fromJson(answer, JsonObject.class);
    jsonObject.getAsJsonArray("data").get(0).getAsJsonObject().getAsJsonObject("vitals");