JSON文字列のオブジェクト構造が不明であるため、JSONオブジェクトのおおよその構造を判断できるように、JavaでJSON文字列を解析し、キーと値のペアを見つけようとしています。
たとえば、ある実行には次のような JSON 文字列が含まれる場合があります。
{"id" : 12345, "days" : [ "Monday", "Wednesday" ], "person" : { "firstName" : "David", "lastName" : "Menoyo" } }
そして、このような別のもの:
{"url" : "http://someurl.com", "method" : "POST", "isauth" : false }
さまざまな JSON 要素を循環し、キーとその値を決定するにはどうすればよいでしょうか? を見ましjackson-core
たJsonParser
。次の「トークン」を取得して、それがどのタイプのトークン (フィールド名、値、配列の開始など) であるかを判断する方法はわかりましたが、実際のトークンの値を取得する方法がわかりません。
例えば:
public void parse(String json) {
try {
JsonFactory f = new JsonFactory();
JsonParser parser = f.createParser(json);
JsonToken token = parser.nextToken();
while (token != null) {
if (token.equals(JsonToken.START_ARRAY)) {
logger.debug("Start Array : " + token.toString());
} else if (token.equals(JsonToken.END_ARRAY)) {
logger.debug("End Array : " + token.toString());
} else if (token.equals(JsonToken.START_OBJECT)) {
logger.debug("Start Object : " + token.toString());
} else if (token.equals(JsonToken.END_OBJECT)) {
logger.debug("End Object : " + token.toString());
} else if (token.equals(JsonToken.FIELD_NAME)) {
logger.debug("Field Name : " + token.toString());
} else if (token.equals(JsonToken.VALUE_FALSE)) {
logger.debug("Value False : " + token.toString());
} else if (token.equals(JsonToken.VALUE_NULL)) {
logger.debug("Value Null : " + token.toString());
} else if (token.equals(JsonToken.VALUE_NUMBER_FLOAT)) {
logger.debug("Value Number Float : " + token.toString());
} else if (token.equals(JsonToken.VALUE_NUMBER_INT)) {
logger.debug("Value Number Int : " + token.toString());
} else if (token.equals(JsonToken.VALUE_STRING)) {
logger.debug("Value String : " + token.toString());
} else if (token.equals(JsonToken.VALUE_TRUE)) {
logger.debug("Value True : " + token.toString());
} else {
logger.debug("Something else : " + token.toString());
}
token = parser.nextToken();
}
} catch (Exception e) {
logger.error("", e);
}
}
ツリーを生成する、または json 要素を循環させて、値に加えて実際のキー名を取得できるようにするクラスが、jackson
または他のライブラリ (gson
または) にありますか?simple-json