Как получить значения ключей внутреннего массива в массиве json - PullRequest
0 голосов
/ 12 мая 2019

Это строка, которую я получаю, и которую я хочу проанализировать как json и получить значения "s", "o", "c" и "p".

{
    "head": {
        "vars": [
            "s",
            "c",
            "o",
            "p"
        ]
    },
    "results": {
        "bindings": [
            {
                "s": {
                    "type": "uri",
                    "value": "http://example.org/data/window"
                },
                "c": {
                    "type": "uri",
                    "value": "http://www.w3.org/ns/sosa/FeatureOfInterest"
                },
                "o": {
                    "type": "uri",
                    "value": "http://example.org/data/window104state"
                },
                "p": {
                    "type": "uri",
                    "value": "http://www.w3.org/ns/ssn/hasProperty"
                }
            },
                        {
                "s": {
                    "type": "uri",
                    "value": "http://example.org/data/earth"
                },
                "c": {
                    "type": "uri",
                    "value": "http://www.w3.org/ns/sosa/FeatureOfInterest"
                },
                "o": {
                    "type": "uri",
                    "value": "http://example.org/data/VCAB-DP1-BP-40location"
                },
                "p": {
                    "type": "uri",
                    "value": "http://www.w3.org/ns/sosa/hasSample"
                }
            }
        ]
    }
}

Это код, который я пробовал до сих пор:

JsonParser jsonParser =  new JsonParser();
JsonElement element = jsonParser.parse(str);
JsonObject obj = element.getAsJsonObject();
JsonObject results = obj.get("results").getAsJsonObject();
for(Map.Entry<String, JsonElement> entry : results.entrySet()) {
            JsonArray array = entry.getValue().getAsJsonObject().getAsJsonArray("bindings");
            for (JsonElement jsonElement : array) {
                 for (Map.Entry<String, JsonElement> entry1 : jsonElement.getAsJsonObject().entrySet()) {
                     System.out.println("Key = " + entry1.getKey() + " Value = " + entry1.getValue() );
                }
            }

То, что я хочу получить, это значения внутреннего массива как такового: "s": "http://example.org/data/earth" "c": "http://www.w3.org/ns/sosa/FeatureOfInterest" и т.п. Вместо этого я получаю сообщение об ошибке:

Exception in thread "main" java.lang.IllegalStateException: Not a JSON Object: [{"s":{"type":"uri","value":"http://example.org/data/window"},"c":{"type":"uri","value":"http://www.w3.org/ns/sosa/FeatureOfInterest"},"o":{"type":"uri","value":"http://example.org/data/window104state"},

(вся строка).

UPDATE Благодаря @Deadpool мне удалось получить значения, но теперь мне нужно получить «внутренние» значения привязок, означающие часть «значение» каждой привязки (s, c, p и o). Мне нужна только эта часть, а не часть типа. Это результат благодаря @Deadpool:

Key = s Value = {"type":"uri","value":"http://example.org/data/window"}
Key = c Value = {"type":"uri","value":"http://www.w3.org/ns/sosa/FeatureOfInterest"}
Key = p Value = {"type":"uri","value":"http://www.w3.org/ns/ssn/hasProperty"}
Key = o Value = {"type":"uri","value":"http://example.org/data/window104state"}

РЕШЕНИЕ Хорошо, для тех, кто заинтересован, мне удалось получить это утверждение, которое было необходимо:

System.out.println("Key = " + entry1.getKey() + " Value = " + entry1.getValue().getAsJsonObject().get("value"));

И это желаемый результат:

Key = s Value = "http://example.org/data/earth"
Key = c Value = "http://www.w3.org/ns/sosa/FeatureOfInterest"
Key = o Value = "http://example.org/data/VCAB-DP1-BP-40location"
Key = p Value = "http://www.w3.org/ns/sosa/hasSample"

Ответы [ 2 ]

4 голосов
/ 12 мая 2019

Проблема в этом утверждении bindings является JsonArray, получите его как JsonArray напрямую

JsonArray array = entry.getValue().getAsJsonObject().getAsJsonArray("bindings");

Решение

for(Map.Entry<String, JsonElement> entry : results.entrySet()) {
        JsonArray array = entry.getValue().getAsJsonArray();
        for (JsonElement jsonElement : array) {
             for (Map.Entry<String, JsonElement> entry1 : jsonElement.getAsJsonObject().entrySet()) {
                 System.out.println("Key = " + entry1.getKey() + " Value = " + entry1.getValue() );
            }
        }
1 голос
/ 14 мая 2019

Вы можете использовать декларативное потоковое сопоставление (DSM) библиотека анализа потока, чтобы легко захватывать данные из XML или JSON

Прежде всего, вы должны определить отображение между данными JSON и вашими полями в формате yaml или JSON.

Вот определения соответствия:

result:     
   type: array
   path: /results/bindings/(s|c|o|p)   // regex
   fields:
     key:
       path: type
     value:  

Java-класс, который вы хотите десериализовать:

public class KeyValue{
    public String key;
    public String value
}   

Java-код для анализа JSON:

DSM dsm=new DSMBuilder(new File("path/to/mapping.yaml")).create(KeyValue.class);
List<KeyValue> list=  (List<KeyValue>)dsm.toObject(jsonData);
// write root object as json
dsm.getObjectMapper().writerWithDefaultPrettyPrinter().writeValue(System.out, list);

Вот вывод:

    [ {
  "key" : "uri",
  "value" : "http://example.org/data/window"
}, {
  "key" : "uri",
  "value" : "http://www.w3.org/ns/sosa/FeatureOfInterest"
}, {
  "key" : "uri",
  "value" : "http://example.org/data/window104state"
}, {
  "key" : "uri",
  "value" : "http://www.w3.org/ns/ssn/hasProperty"
}, {
  "key" : "uri",
  "value" : "http://example.org/data/earth"
}, {
  "key" : "uri",
  "value" : "http://www.w3.org/ns/sosa/FeatureOfInterest"
}, {
  "key" : "uri",
  "value" : "http://example.org/data/VCAB-DP1-BP-40location"
}, {
  "key" : "uri",
  "value" : "http://www.w3.org/ns/sosa/hasSample"
} ]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...