简体   繁体   English

在 JsonArray (javax.json.JsonArray) 中通过键或值查找 JsonObject 使用 Java 8 Lambas

[英]Find JsonObject in JsonArray (javax.json.JsonArray) By Key or Value Using Java 8 Lambas

I haven't been able to find a concise/up-to-date answer on how to use Java 8 Lambdas to quickly locate a JsonObject in a JsonArray ( javax.json.JsonArray ).我无法找到关于如何使用 Java 8 Lambdas 在JsonArrayjavax.json.JsonArray )中快速定位JsonObject的简明/最新答案。 All the answers about loops, which are too verbose.所有关于循环的答案,太冗长了。

Suppose I have假设我有

JsonArray answersArray  = ...

The array is数组是

[   {
        "activityQuestionId": "875",
        "questionType": "STARTTIME",
        "answer": "12:45am"
    }, {
        "activityQuestionId": "876",
        "questionType": "ENDTIME",
        "answer": "1:00am"
    }, 
    ...
    {
        "activityQuestionId": "SPECIAL",
        "questionType": "DROPDOWN",
        "answer": "756", 
        "extra": "SPECIAL/EXTRA"
    }
]

Normally, I can do通常情况下,我可以

JsonArray answersArray  = ...
JsonObject obj1 = answersArray.getJsonObject(1); // This brings back 2nd object 
String str = obj1.getString("answer"); // This brings back 1:00am answer in 2nd object

I need to do the following:我需要执行以下操作:

  • Find By Key: Locate JsonObject having the key "extra" .按键查找:找到具有键"extra"JsonObject Only 1 object has it (the last), so that's the one I should get.只有 1 个 object 有它(最后一个),所以这是我应该得到的。
  • Find By Value of Some Key: Locate JsonObject having "activityQuestionId": "SPECIAL" .按某个键的值查找:找到具有"activityQuestionId": "SPECIAL"JsonObject The same last object should be returned.应该返回相同的最后 object。

JsonArray : https://docs.oracle.com/javaee/7/api/javax/json/JsonArray.html JsonArrayhttps://docs.oracle.com/javaee/7/api/javax/json/JsonArray.html

Try this.尝试这个。 This should work这应该工作

 final Optional<Object> extra = IntStream.range(0, jsonArray.length())
                .mapToObj(i -> getJsonObject(jsonArray, i))
                .filter(Objects::nonNull)
                .map(this::getObject)
                .filter(Objects::nonNull)
                .findFirst();
     //if extra.isPresent() then do extra.get() to get the value
    }

   //Instead of returning a generic type try to return specific type
   //Better Exception handling
    private Object getObject(JSONObject entry) {
        try {
            return entry.get("extra");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    private JSONObject getJsonObject(JSONArray jsonArray, int i) {
        try {
            return jsonArray.getJSONObject(i);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

This is not a complete solution.这不是一个完整的解决方案。 This should give you some idea about how to approach.这应该给你一些关于如何接近的想法。 You should check out how to handle exceptions inside lambdas if you want to use lamdas for this kinda code, because json processing throws lots of checked exceptions.如果您想将 lamdas 用于此类代码,您应该查看如何在 lambdas 中处理异常,因为 json 处理会引发大量检查异常。 And you cannot just throw those from inside lambdas, you need to handle it.而且你不能只从 lambdas 中抛出这些,你需要处理它。

You need to think if using Streams is a good approach for this scenario or if its a over kill.您需要考虑使用 Streams 是否适合这种情况,或者是否过度杀戮。

Locate JsonObject having key "extra"找到具有“额外”键的 JsonObject

JsonObject extraKeyJsonObject = value.stream()
        .map(JsonValue::asJsonObject)
        .filter(jo -> jo.containsKey("extra"))
        .findFirst()
        .orElse(null);// or something else

Locate JsonObject having "activityQuestionId": "SPECIAL"找到具有“activityQuestionId”的 JsonObject:“SPECIAL”

JsonObject activityIdSpecialJsonObject = value.stream()
        .map(JsonValue::asJsonObject)
        .filter(jo -> "SPECIAL".equals(jo.getString("activityQuestionId", null)))
        .findFirst()
        .orElse(null);// or something else

Solution解决方案

List<JsonValue> objects1 = answersArray.stream().filter(obj -> 
            ((JsonObject)obj).getString("extra") != null).collect(Collectors.toList());

List<JsonValue> objects2 = answersArray.stream().filter(obj ->      
            "SPECIAL".equals(((JsonObject)obj).getString("activityQuestionId")).collect(Collectors.toList());

Try This...尝试这个...

JsonObject jsonObject= answersArray.getJsonObject(1) // 1 is the second index in the json array
String activityQuestionId= jsonObject.getString("activityQuestionId");
String questionType= jsonObject.getString("questionType");

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

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