需要构建实用程序,该实用程序将使用JSON SIMPLE api根据嵌套JSON文件中的键检索值



嗨,我需要构建一个实用程序,它将以键的形式进行输入,如下所示: source.payload.header.version 它应该从下面的示例 json 返回版本 1.1.1

"source":{
"payload":{
"Header":{
"version":"1.1.1"

我是 json 和 json simple的新手

我在要使用的库中找不到本机实现,它可以处理这种请求。所以我想出了我自己的小代码片段,可能会对你有所帮助。

private static Object getNestedValue(final String path, JSONObject obj) {
String currentKey;
String currentPath = path;
while (true) {
// Get current key with tailing '.'
currentKey = currentPath.substring(0, currentPath.indexOf('.') + 1);
// Remove the current key from current path with '.'
currentPath = currentPath.replace(currentKey, "");
// Remove the '.' from the current key
currentKey = currentKey.replace(".", "");
// Check if the current key is available
if (obj.containsKey(currentKey))
obj = (JSONObject) obj.get(currentKey);     // This can cause an Class Cast exception, handel with care
else if (currentKey.isEmpty())                  // Check if the currentKey is empty
return obj.get(currentPath);                // Return the result
else
return null;
}
}

最新更新