【发布时间】:2019-11-28 14:37:35
【问题描述】:
我正在尝试使用动态键获取 json(具有未知模板)值;
"user.specs.id"
问题是我的 json 结构不是静态的,因此我无法将其解析为 java 对象或使用 Gson 方法获取其属性。
{
"user": {
"specs": {
"id": 12222,
"name": "foo"
}
}
}
有没有办法用某个键从任何 json 中提取一些数据?
编辑:我有一个类似的服务方法;
public Object getValueByKey(String json, String key);
“json”参数的可能值;
{"name": "test"} //possible key "name"
{"user": {"id": 1232}} //possible key "user.id"
{"cars": ["car1", "car2"]} //possible key "cars[0]"
【问题讨论】:
-
有几个库旨在解析没有固定数据模型的 JSON,例如GSON
-
@Guy 不,不是。我不是在寻找像“user”这样的单个键,而是像“user.specs.id”这样的多个组合键
-
您可以使用
JsonPath库。Jackson允许与JsonPointer类似的解决方案。查看相关问题:Parsing deeply nested JSON properties with Jackson、Iterate over a large JSON Array with JSONPath、how to parse a huge JSON file without loading it in memory