私はこのようなjsonテンプレートを持っています。これで特定のディレクトリにjsonキーを置くと、すべてのディレクトリにキーが置かれます(JsonPath.parse(String).put)
{
"parent": {
"dir1": {
"key11": {
"min": 1,
"max": 100
},
"key12": {
"sample1": "txt",
"sample2": "100.25"
}
},
"dir2": {
"key21": {
"min": 1,
"max": 100
},
"key22": {
"sample1": "USD",
"sample2": "100.25"
}
}
}
}
Iは、JSONを解析して(繰り返しながら)parent.dir1は、例えばためのいくつかの特定のキーを持っているかどうかを確認するためのロジックを有します"goldenKey" keyが見つからない場合は、jsonpathの "key(goldenKey)"をput()します。 JsonPath.parse(jsonString).put(jsonpath、key、value).json();
キーを置くjsonPathを取得するには、現在のjsonPathを "。"で分割して1つのノードに戻します。最後からそれをキーに変換する必要があります。
try {
//set jsonpath, if key not found then catch
JsonPath.parse(json).set("$.parent.dir1.goldenKey", "golden").json();
} catch (final PathNotFoundException e) {
//json path of the key
String jsonpath = "$.parent.dir1.goldenKey";
//get the key by getting last index of "."
final String key = jsonpath.substring(jsonpath.lastIndexOf(".") +1);
jsonpath = jsonpath.substring(0, jsonpath.lastIndexOf("."));
JsonPath.parse(json).put(jsonpath, "goldenKey", "golden").json();}
コード以下のような問題は、それがDIR1とdir23
の両方にキーと値をしてください置く代わりに、与えられたJSONパス上のキー、値を置く、ということ(すなわちDIR1このコードでは)あり説明が明確でない場合は私に知らせてください。
こんにちは、私の問題を調べる時間を取ってくれてありがとう。 あなたが参照している何のために私の推測では、この行にある: '文字列jsonpath =「$ .parent.dir1.goldenKey」;' は、それが実際に** giveMeAJsonPathForGivenField(文字列フィールド)**、jsonPathsそうのような方法であり、他のクラスではあらかじめ定義されています。私はそれを置く必要があるキー(goldenKey)とjsonpathを得るために、そのjsonpathの値_($ parent.dir1.goldenKey)_で遊ばなければなりません_ In line ' jsonpath = jsonpath.substring(0、jsonpath.lastIndexOf( "。")); ' jsonpathに正しい値があります: "$ .parent.dir1" – Raghu