我需要获取一个json字符串,它是一个更大的json的一部分。作为简化示例,我只想提取file01,并且需要将json对象作为字符串。
{
"file01": {
"id": "0001"
},
"file02": {
"id": "0002"
}
}
因此,在代码中类似:
String file01 = JsonPath.parse(jsonFile).read("$.file01").toJson();
System.out.println(file01); // {"id":"0001"}
我想使用库JsonPath,但是我不知道如何获得所需的东西。
任何帮助表示赞赏。谢谢!
中的默认解析器JsonPath
会将所有内容读取为,LinkedHashMap
因此的输出read()
将为Map
。您可以使用诸如Jackson或Gson之类的库将其序列Map
化为JSON字符串。但是,您也可以JsonPath
在内部为您执行此操作。
为此,JsonPath
您可以配置JsonPath
的另一种实现AbstractJsonProvider
,使您可以动手以JSON格式解析结果。在下面的例子中,我们使用GsonJsonProvider
和输出read()
方法是一个JSON字符串。
@Test
public void canParseToJson() {
String json = "{\n" +
" \"file01\": {\n" +
" \"id\": \"0001\"\n" +
" },\n" +
" \"file02\": {\n" +
" \"id\": \"0002\"\n" +
" }\n" +
"}";
Configuration conf = Configuration.builder().jsonProvider(new GsonJsonProvider()).build();
JsonObject file01 = JsonPath.using(conf).parse(json).read("$.file01");
// prints out {"id":"0001"}
System.out.println(file01);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句