How to search for values inside Json file

独自空忆成欢 提交于 2019-12-13 11:06:48

问题


I have this json below and i need to get the value of "ID" which is "SMGL". i'm using Gson to save the json from file. how can I search for this?

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

回答1:


how about using ObjectMapper

final String json = "{\"yourjson\": \"here\", \"andHere\": ... }";
final ObjectNode node = new ObjectMapper().readValue(json, ObjectNode.class);

if (node.has("ID")) {
    System.out.println("ID: " + node.get("ID"));
} 

This is one of the many ways:

Adding for GSON,

String json = "your json here" // you can also read from file etc
    Gson gson = new GsonBuilder().create();
    Map jsonMap = gson.fromJson(json, Map.class);
    System.out.println(jsonMap.get("ID"));

Explore more.

thanks




回答2:


You could try JSONPath an extraordinary java library.

The expressions are very simple like JQuery array access.

String expression = "$.glossary.GlossDiv.GlossList.GlossEntry.ID"

String result = JsonPath.read(json_input, expression);


来源:https://stackoverflow.com/questions/46443379/how-to-search-for-values-inside-json-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!