我正在尝试解析JsonNode
对象,以从JsonNode
对象中检索以“ s”开头的元素列表。
我的JSON
:
{"Result":[
{
"user_name":"jack",
"email":"admin@gmail.com",
"Phone":"111111111",
"s_update":"2019-06-06 11:40:38",
"s_created_on":"2019-06-02 17:40:38",
"s_created_by":"admin",
"s_id":"ad9db8a330091c2e1bb4b961935"
}
]}
预期输出:
{s_created_on=2019-06-02 17:40:38,s_created_by=admin,
s_id=ad9db8a330091c2e1bb4b961935}
关于正确方法的任何想法吗?
答案 0 :(得分:0)
您只需要遍历JSON Array
中的所有项目,并为每个项目遍历所有字段。如果字段名称以s
开头,请将其删除。参见以下示例:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;
public class Test {
public static void main(String[] args) throws IOException {
File jsonFile = new File("./src/main/resources/test.json");
ObjectMapper jsonMapper = new ObjectMapper();
ObjectNode root = (ObjectNode) jsonMapper.readTree(jsonFile);
ArrayNode result = (ArrayNode) root.get("Result");
for (JsonNode node : result) {
Iterator<Entry<String, JsonNode>> fields = node.fields();
while (fields.hasNext()) {
Entry<String, JsonNode> next = fields.next();
if (!next.getKey().startsWith("s")) {
fields.remove();
}
}
}
System.out.println(result);
}
}
上面的代码显示:
[{"s_update":"2019-06-06 11:40:38","s_created_on":"2019-06-02 17:40:38","s_created_by":"admin","s_id":"ad9db8a330091c2e1bb4b961935"}]