无法从JSON中提取值

时间:2014-02-27 15:51:21

标签: java json parsing

示例:

{"name":"tv.twitch:twitch:5.16"}

{"name":"tv.twitch:twitch-external-platform:4.5","extract":{"exclude":["META-INF/"]},"natives":{"windows":"natives-windows-${arch}"},"rules":[{"os":{"name":"windows"},"action":"allow"}]}

这些行来自JSONArray,我想提取“本机”部分。问题是,并非JSONArray中的所有项都具有“本机”值。这是我当前提取“名称”值

的代码
JSONObject json = new JSONObject(readUrl(url.toString()));
JSONArray jsonArray = json.getJSONArray("libraries");

ArrayList<String> libraries = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject next = jsonArray.getJSONObject(i);
    String lib = next.getString("name");
    libraries.add(lib);
}

由于我不熟悉java / JSON解析,所以我不确定这一点,但数组中没有“natives”值的对象会导致程序结束吗?

2 个答案:

答案 0 :(得分:1)

您可以使用JSONObject中的has方法来确定它是否包含指定的密钥。

  

确定JSONObject是否包含特定密钥。

在你的情况下,你可以这样做:

JSONObject json = new JSONObject(readUrl(url.toString()));
if(json.has("natives")) {
   //Logic to extract natives
} else {
   //Logic to extract without natives
}

我认为这些简单的界限应该足以满足您的要求。请参阅API:here

答案 1 :(得分:1)

您似乎想要在JSON Pointer s /name/extract/natives/windows提取内容。

在这种情况下,使用this library(取决于杰克逊),就像这样简单:

// All of these are thread safe
private static final ObjectReader READER = JacksonUtils.getReader();
private static final JsonPointer NAME_POINTER = JsonPointer.of("name");
private static final JsonPointer WINDOWS_POINTER 
    = JsonPointer.of("extract", "native", "windows");

// Fetch content from URL
final JsonNode content = READER.readTree(url.getInputStream());
// Get content at pointers, if any
final JsonNode nameNode = NAME_POINTER.path(content);
final JsonNode windowsNode = WINDOWS_POINTER.path(content);

然后,要检查节点是否确实存在,请检查.isMissingNode()

if (windowsNode.isMissingNode())
    // deal with no windows content

或者,使用.get()代替.path(),然后检查null

相关问题