[英]Search multiple JSON files and extract values based on some condition in Java
I have a scenario where there are multiple JSON files.我有一个场景,其中有多个 JSON 文件。 I want to extract the values from all the JSON files matching the condition which I provide.我想从与我提供的条件匹配的所有 JSON 文件中提取值。
For Example:例如:
{
"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"
}
}
}
}
}
I have a condition to extract all the GlossEntryID
which has "Acronym": "SGML"
我有一个条件来提取所有具有"Acronym": "SGML"
的GlossEntryID
I am very new to JSON so any lead would be appreciated.我对 JSON 很陌生,所以任何线索都将不胜感激。
try below code to parse json and check condition尝试下面的代码来解析 json 并检查条件
try {
String json = "{" +
" \"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\"" +
" }" +
" }" +
" }" +
" }" +
"}";
// parse the whole JSON string into JSONObject
JSONObject obj = new JSONObject(json);
// retrieve glossary obj from JSON
JSONObject glossary = obj.getJSONObject("glossary");
// retrieve GlossDiv obj from glossary
JSONObject GlossDiv = glossary.getJSONObject("GlossDiv");
// retrieve GlossList obj from GlossDiv
JSONObject GlossList = GlossDiv.getJSONObject("GlossList");
// retrieve GlossEntry obj from GlossList
JSONObject GlossEntry = GlossList.getJSONObject("GlossEntry");
// Check condition
if (GlossEntry.getString("Acronym").equalsIgnoreCase("SGML")) {
String id = GlossEntry.getString("ID");
}
} catch (JSONException e) {
e.printStackTrace();
}
If you are using Jayway JsonPath
, you can simply achieve this as follows:如果您使用Jayway JsonPath
,您可以简单地实现如下:
Maven Dependency Maven 依赖
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
Code Snippet代码片段
DocumentContext jsonContext = JsonPath.parse(jsonStr);
List<String> idList = jsonContext.read("$.glossary.GlossDiv.GlossList.GlossEntry[?(@.Acronym == 'SGML')].ID");
System.out.println(idList.toString());
Console Output控制台输出
["SGML"] [“SGML”]
Then you can read those JSON files either sequentially or parallelly to combine these results.然后您可以顺序或并行读取这些 JSON 文件以组合这些结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.