如何从路径中获取JSONObject中的嵌套值?

时间:2016-11-24 10:07:02

标签: java android json parsing

我尝试实现给定任何JSONObject和路径String的函数,将返回与路径对应的对象属性。

例如,给出这个json:

{
"name": "John", 
"friends": [
  {"name": "Paul",
   "age":42},
  {"name": "Peter",
   "age":24}
 ],
"address": {"city": "London"}
}
  • getAttribute(jsonObject, "name")应该返回"John"
  • getAttribute(jsonObject, "address.city")应该返回"London"
  • getAttribute(jsonObject, "friends[0].name")应该返回"Paul"

请注意,此JSON只是一个示例,jsonObject没有预定义的结构,可以表示任何有效的json。

我编写了第一个实现前两种情况的版本,但处理数组和多级数组"foo[0][0].bar"给这个函数带来了很多复杂性。

是否有推荐的工具/库/方法从JSONObject获取属性给定"复杂"路径?

4 个答案:

答案 0 :(得分:3)

如果我正确理解了您的问题,您可能已经回答here

或者,您也可以尝试以下开源库:

https://github.com/jayway/JsonPath

答案 1 :(得分:2)

Stefan Goessner的JSONPath standard涵盖了更复杂的语法,但它也处理了经典的javascript" JSON路径语法。

使用JayWay's implementation for Java,回答这个问题很简单:

public String getAttribute(JSONObject json, String path) {
    return JsonPath.read(json.toString(), path);
}

答案 2 :(得分:1)

我如何解决问题:

  import io.restassured.path.json.JsonPath;


String  id = JsonPath.given(Myobject).get(path).toString();

使用这个库的好处是即使你的路径有数组,它也可以处理 那个

示例:String path="Myobject[0].id"

答案 3 :(得分:0)

您可以使用GSON库并将您的json字符串解析为POJO类。

private final static Gson GSON = new GsonBuilder().create();

public static <T> T fromJSON(String json, Class<T> clazz) {
    try {
        return GSON.fromJson(json, clazz);
    } catch (JsonSyntaxException e) {
        LOGGER.warn("Could not deserialize object", e);
    }
    return null;
}

根据您的JSON结构设计您的模型类。

相关问题