I am changing my JSON library from org.json to Jackson and I want to migrate the following code:
JSONObject datasets = readJSON(new URL(DATASETS));
JSONArray datasetArray = datasets.getJSONArray("datasets");
Now in Jackson I have the following:
ObjectMapper m = new ObjectMapper();
JsonNode datasets = m.readTree(new URL(DATASETS));
ArrayNode datasetArray = (ArrayNode)datasets.get("datasets");
However I don't like the cast there, is there the possibility for a ClassCastException
? Is there a method equivalent to getJSONArray
in org.json
so that I have proper error handling in case it isn't an array?
ベストアンサー1
はい、Jackson の手動パーサーの設計は他のライブラリとはかなり異なります。特に、JsonNode
他の API の配列ノードに通常関連付けられる関数のほとんどが に含まれていることに気付くでしょう。そのため、 を使用するために にキャストする必要はありませんArrayNode
。次に例を示します。
: : JSON:
{
"objects" : ["One", "Two", "Three"]
}
コード:
final String json = "{\"objects\" : [\"One\", \"Two\", \"Three\"]}";
final JsonNode arrNode = new ObjectMapper().readTree(json).get("objects");
if (arrNode.isArray()) {
for (final JsonNode objNode : arrNode) {
System.out.println(objNode);
}
}
出力:
"1
2
3"
反復処理の前に、ノードが実際に配列であることを確認するためにを使用していることに注意してくださいisArray
。データ構造に絶対的な自信がある場合、このチェックは不要ですが、必要な場合は使用できます (これは他のほとんどの JSON ライブラリと変わりません)。