Это строка, которую я получаю, и которую я хочу проанализировать как 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"