0

我正在尝试解析JsonNode对象以从对象中检索以“s”开头的元素列表JsonNode

我的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}

关于正确方法的任何想法?

4

1 回答 1

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"}]
于 2019-06-19T08:07:10.037 回答