JAVA Json 自动解析特定值

JAVA Json automatic parsing for specific value

注:这是org.json.simple

在下面的例子中,我总是想要 "weWantThis" 值。 例如,我们有 Json:

示例 1。

{
    "Header1": {
        "Basex": "ws",
        "Random": {
            "Something": "information"
        },
        "age": 22,
        "Type": "Apa",
        "correlation": "x",
        "weWantThis": "somethingHere"
    }
}

示例 2.

{
    "Header1": {
        "useful": "yes",
        "code": 200,
        "creation": {
            "isValid": "yes",
            "date": 25,
            "items": [
                "pc"
            ],
            "weWantThis": "somethingHere"
        }
    }
}

正如您所见,Json 的格式完全不同,甚至可能更加不同。目标是自动检索 "weWantThis" 的值。即所有其他 headers 等都是未知的,当然 "weWantThis" 除外。如果它甚至不存在,只需 return null。 所以基本上需要进行自动解析,直到找到 "weWantThis" 。不知道如何做到这一点。任何帮助表示赞赏。谢谢!

您首先需要将此字符串加载到 JSONObject

类似于:

JSONObject ob = new JSONObject(string_content)

现在您需要遍历每个键值对。 该值可以是简单对象(布尔、字符串、整数等)或 JSONArray 或 JSONObject。在后两种情况下,您都可以递归调用您刚刚在值上编写的相同函数。在 JSONArray 的情况下,您将必须遍历数组中的每个项目并递归调用此函数。

你继续这样做,直到你发现密钥是 "weWantThis"

要查找给定 JSONObject 中的所有键,您可以使用此处建议的内容:

https://www.codevoila.com/post/65/java-json-tutorial-and-example-json-java-orgjson#toc_5

How to parse JSON in Java

从 JSON 字符串中,只需执行 indexOf("\"weWantThis\": ") 然后解析出下一个值。当您只是在寻找没有结构的文字时,为什么 运行 它通过 JSON 解析器?

您可以使用JSON路径库。它支持通配符,并支持通过 json 结构导航来检索任意键的值。

JSONPath

您甚至可以在此处尝试您的具体示例 -

Try out JSONPath

输入您想要的 JSON 然后尝试此路径 -

$..weWantThis

下面是具体实现 -

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.PathNotFoundException;

Object document = Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS).jsonProvider()
            .parse(<jsonString>);
String value = JsonPath.read(document, "$..weWantThis");