How to search for values inside Json file

2019-09-22 11:52发布

问题:

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);


标签: java json gson