简体   繁体   中英

Jackson — parse json using xpath or similar

I have some json and it's fairly complex -- (a bit too complex and open-ended to model using something like gson), and I need to extract string values from certain nodes into a list of strings.

The following code works, but due to the way my json works -- it's grabbing lots of extra stuff that I don't want (note: I don't own the json schema)

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

The contents of Json is fairly complex (Jira filter export) which looks like this:

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

Assertions: I always want to extract issues[x].key and not any of the subkeys. I would prefer to extract this into a list, but any normal data structure is fine. I'm already using Jackson -- but gson is also an option if there's a sane way of doing so.

Thanks for the assist!

JsonPath is xpath for json, and it has a Java implementation . Here is a working example to get issue keys without subkeys:

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

 }

Example usage:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM