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

时间:2020-01-23 08:17:18

标签: java arrays json nested gson

我不能使用org.json package

问题

使用HTTP GET方法从患者病历数据库中检索信息。查询https://jsonmock.hackerrank.com/api/medical_records以查找所有记录。查询结果是分页的,可以通过附加到查询字符串?&page=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
  • timestamp:生成记录的时间戳(以UTC为单位,以毫秒为单位)
  • userId:已为其记录交易的用户的ID
  • userName:已为其记录交易的患者/用户的名称
  • userDob:用户的出生日期,格式为DD-MM-YYYY
  • vitals:对象,用户的生命力
  • vitals.bloodPressureDiastole:用户的舒张压读数,mmHg
  • vitals.bloodPressureSystole:用户的收缩压读数,mmHg
  • vitals.pulse:用户的脉搏率,每分钟心跳数
  • vitals.breathingRate:用户的呼吸速率,即每分钟呼吸次数
  • vitals.bodyTemperature:用户的体温,华氏度
  • diagnosis.id:诊断的ID
  • diagnosis.name:诊断出的疾病的名称
  • diagnosis.severity:诊断出疾病的严重程度
  • doctor:对象,诊断出状况的医生
  • doctor.id:诊断出该病的医生的证件
  • doctor.name:诊断出该病的医生的名字
  • meta:对象,用户的元信息
  • meta.height:用户的当前身高,厘米
  • meta.weight:用户当前的体重,磅

根据以下条件获取所有病历并进行过滤:

ageStart ≤ the age of the user at the time of the record creation timestamp ≤ ageEnd

对于匹配第一个criteria, bloodPressureDiastole - bloodPressureSystole > 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);


需要访问“重要”元素-以下是我的尝试

                        JsonParser jsonParser = new JsonParser();
                        JsonObject vitals = jsonParser.parse(json)
                            .data.get(i).getAsJsonObject().get("vitals");
                        int bpdy = vitals.get("bloodPressureDiastole").getAsInt();
                        //JsonArray vitals = data.get(i).getAsJsonArray("vitals");
                        //int bpdy = data.get(i).getAsJsonArray("vitals").getAsJsonObject().get("bloodPressureDiastole").getAsInt();


                       // bpd.add(bpdy);
                        //int bpsy = data.get(i).getAsJsonObject("vitals").getAsJsonObjectAsJsonObject("bloodPressureSystole").getAsInt();
                        //int bpsy=data.get(i).getAsJsonObject("vitals").getAsJsonObject().get("bloodPressureSystole").getAsInt();
                        //bps.add(bpsy);
                    }


                }
                in.close();
                startPage++;

            }
            catch (Exception ex){
                ex.printStackTrace();
            }
        }

        //current age

        for (int i = 0; i < dobs.size(); i++){
            SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
            try{
            Date dobform = format.parse(dobs.get(i));

                //utc date
            Date date = new Date(times.get(i));
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
            String tsform = sdf.format(date);
            Date tsformcom = format.parse(tsform);

            int userage = calculateAgeWithJava7(dobform, tsformcom);
            if ((userage==ageStart|| userage>ageStart) & (userage==ageEnd || userage<ageEnd)){
                int actualbpdiff=bpd.get(i)-bps.get(i);
                if (actualbpdiff > bpDiff){
                    results.add(ids.get(i));
                }

            }

            }catch (Exception ex) {
            ex.printStackTrace();
            }





        }

        return results;


    }

    public static int calculateAgeWithJava7(
  Date birthDate,
  Date currentDate) {
    DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
    int d1 = Integer.parseInt(formatter.format(birthDate));
    int d2 = Integer.parseInt(formatter.format(currentDate));
    int age = (d2 - d1) / 10000;
    return age;
}

}

2 个答案:

答案 0 :(得分:1)

不知道为什么已经解析了JSON后就认为您需要一个新的JsonParser

这样我们就可以看到您正在解析的内容,这是其中的一部分:

{
  "page": 1,
  "per_page": 10,
  "total": 99,
  "total_pages": 10,
  "data": [
    {
      "id": 1,
      "timestamp": 1565637002408,
      "diagnosis": {
        "id": 3,
        "name": "Pulmonary embolism",
        "severity": 4
      },
      "vitals": {
        "bloodPressureDiastole": 154,
        "bloodPressureSystole": 91,
        "pulse": 125,
        "breathingRate": 32,
        "bodyTemperature": 100
      },
      "doctor": {
        "id": 2,
        "name": "Dr Arnold Bullock"
      },
      "userId": 2,
      "userName": "Bob Martin",
      "userDob": "14-09-1989",
      "meta": {
        "height": 174,
        "weight": 172
      }
    },
    ...
  ]
}

Java是一种面向对象的语言。用它!创建一个用于存储数据值的类,然后使用单个List<Data>

List<Data> dataList = new ArrayList<>();

您已经必须迭代data,所以让我们从那里开始。

不要多次查找数组中的对象。不利于性能,不利于代码的可读性。

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);
}

其中Data类是:

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

    // Getters and setter here
}

答案 1 :(得分:-1)

    JsonObject jsonObject = gson.fromJson(answer, JsonObject.class);
    jsonObject.getAsJsonArray("data").get(0).getAsJsonObject().getAsJsonObject("vitals");

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