我有一些 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 也是一个选择。
感谢您的协助!
JsonPath 是 json 的 xpath,它有一个 Java 实现。 这是一个获取没有子密钥的问题密钥的工作示例:
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());
}
}
使用示例:
ObjectMapper objectMapper = new ObjectMapper();
List<String> keys = objectMapper.readValue( .., ExportFilter.class).getKeys();
检查杰克逊
at
和jsonPointer
这里jackson.core,我正在使用类似的东西:
JsonNode input = objectMapper.readTree(fileStream);
String device_name = input.at("/device/name").asText();
JsonNode fq_name_list = input.at("/abstract_config/fq_name");
if (fq_name_list.isMissingNode()) continue;
String fq_name = fq_name_list.get(fq_name_list.size() - 1).asText();
logger.info(" device:{} abstract_config:{}",device_name,fq_name);