【问题标题】:Jackson -- parse json using xpath or similarJackson -- 使用 xpath 或类似方法解析 json
【发布时间】:2019-03-01 13:42:37
【问题描述】:

我有一些 json,它相当复杂——(使用 gson 之类的东西建模有点过于复杂和开放),我需要将字符串值从某些节点提取到字符串列表中。

以下代码有效,但由于我的 json 工作方式 - 它获取了很多我不想要的额外内容(注意:我不拥有 json 架构)

ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(json);
        List<JsonNode> keys = node.findValues("key") ;
for(JsonNode key: keys){
         System.out.println(key.toString());
}

Json 的内容相当复杂(Jira 过滤器导出),如下所示:

{
    "issues": [
    {
        "key":"MIN-123",
        ...
        "fields":{
             "key":"A_Elric"
        }
    }
    ]
}

断言: 我总是想提取 issues[x].key 而不是任何子键。我更愿意将它提取到一个列表中,但任何普通的数据结构都可以。我已经在使用 Jackson 了——但如果有合理的方法,gson 也是一种选择。

感谢您的帮助!

【问题讨论】:

    标签: java json jackson jira jackson2


    【解决方案1】:

    JsonPath 是 json 的 xpath,它有一个 Java implementation。 这是一个获取没有子键的问题键的工作示例:

    import com.jayway.jsonpath.Configuration;
    import com.jayway.jsonpath.JsonPath;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.List;
    
    public class JsonPathTest {
    
        public static String ROOT_ARRAY = "issues";
        public static String KEY = "key";
        // get all KEYs right under ROOT array
        public static String jsonPath = String.format("$.%s[*].%s", ROOT_ARRAY, KEY);
    
        public static void main(String[] args) {
            try {
                String jsonStr = new String(Files.readAllBytes(Paths.get("c:/temp/xx.json")));
                Object jsonObj = Configuration.defaultConfiguration().jsonProvider().parse(jsonStr);
                List<String> keys = JsonPath.parse(jsonObj).read(jsonPath);
                System.out.println(keys);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    【讨论】:

      【解决方案2】:
      public class ExportFilter{
          private static final String KEY = "key";
          private List<Map<String,Object>> issues = new ArrayList<>();
      
          //getters and setters
      
          @JsonIgnore
          public List<String> getKeys(){
               return issues.stream()
                      .map(issue-> issue.get(KEY))
                      .filter(Objects::nonNull)
                      .map(Objects::toString)
                      .collect(toList());
          }
      
       }
      

      示例用法:

       ObjectMapper objectMapper = new ObjectMapper();
       List<String> keys = objectMapper.readValue( .., ExportFilter.class).getKeys();
      

      【讨论】:

        猜你喜欢
        • 2017-06-28
        • 2013-03-17
        • 1970-01-01
        • 1970-01-01
        • 2012-11-08
        • 1970-01-01
        • 2012-07-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多