JavaでJSONを扱うためのライブラリはたくさんあるなぁ
どれを使ったらいいんだろう?
ちょっと古い記事だけど、A Review of 5 Java JSON Libraries が参考になりそう。
この記事で取り上げているのは次の5つ。
www.json.orgに18ものライブラリが掲載されていると書いてあるが、
その中からどういう基準で5つを選んだのか気になるところ。
それでも、これらの中のどれかを状況に合わせて選択すれば今を生きていくには十分だろう。
「とりあえずJSON使っておく?」
みたいな状況だったら JSON.simple を使えば良さそう。
ところで、AndroidのSDKにはorg.json.JSONObjectなどが用意されている。
パッケージ名から類推して org.json のコードが使われているのかと思っていたら間違いだった。
[platform/libcore.git] / json / src / main / java / org / json / JSONObject.java
ここのソースのコメントに、
// Note: this class was written without inspecting the non-free org.json sourcecode.
と書いてある。
オリジナルってことかな?
2011年3月31日木曜日
2011年3月1日火曜日
JavaでXPathを使ったことがあった
<?xml version="1.0" encoding="UTF-8"?>
<hello>
<item>
<world attr="value1"/>
</item>
<item>
<world attr="value2"/>
</item>
</hello>
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XPathSample {
public static void main(String[] args) throws Exception {
XPathExpression xpath =
XPathFactory.newInstance()
.newXPath()
.compile("//world[@attr='value2']");
Document document =
DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(new File("hello.xml"));
NodeList nodeList = (NodeList) xpath.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); ++i) {
Node node = nodeList.item(i);
NamedNodeMap attributes = node.getAttributes();
String value = attributes.getNamedItem("attr").getNodeValue();
System.out.println(value);
}
}
}
登録:
コメント (Atom)
