0

我有下面的 json 字符串,我想从这个字符串中提取"id"之后的所有字段"number":(15124,13498)

我正在尝试通过java代码中的jsonpath来做到这一点:

String pd = JsonPath.read(jsonString, "$.response.data.number.id");`

但是由于错误的 jsonpath,我得到了一个异常,我应该为获取"id"after"number"字段而写什么 jsonpath?

json字符串下方:

{
    "response": {
        "code": 200,
        "msg": "Success",
        "data": {
            "number": {
                "id": "13498",
                "name": "(Not in used) Daniel - 30138444",
                "network_id": 1,
                "network_type": "Facebook",
                "currency": "USD",
                "currency_info": {
                    "prefix": "$",
                    "postfix": "",
                    "name": "US Dollars"
                },
                "timezone": {
                    "id": 92,
                    "code": "PST",
                    "region": "America",
                    "locality": "Los_Angeles",
                    "offset": -7,
                    "facebook_code": 1
                }
            }
        }
    }
}
4

2 回答 2

0

这工作正常

 String pd = JsonPath.read("{\n" +
            "    \"response\": {\n" +
            "        \"code\": 200,\n" +
            "        \"msg\": \"Success\",\n" +
            "        \"data\": {\n" +
            "            \"number\": {\n" +
            "                \"id\": \"13498\",\n" +
            "                \"name\": \"(Not in used) Daniel - 30138444\",\n" +
            "                \"network_id\": 1,\n" +
            "                \"network_type\": \"Facebook\",\n" +
            "                \"currency\": \"USD\",\n" +
            "                \"currency_info\": {\n" +
            "                    \"prefix\": \"$\",\n" +
            "                    \"postfix\": \"\",\n" +
            "                    \"name\": \"US Dollars\"\n" +
            "                },\n" +
            "                \"timezone\": {\n" +
            "                    \"id\": 92,\n" +
            "                    \"code\": \"PST\",\n" +
            "                    \"region\": \"America\",\n" +
            "                    \"locality\": \"Los_Angeles\",\n" +
            "                    \"offset\": -7,\n" +
            "                    \"facebook_code\": 1\n" +
            "                }\n" +
            "            }\n" +
            "        }\n" +
            "    }\n" +
            "}", "$.response.data.number.id");
    System.out.println(pd);

输出:

  13498

检查您是否传递JSON正确jsonString

于 2014-07-10T12:02:31.477 回答
-1

我认为根据您要查找的内容,您将获得一个 List 作为输出。我也觉得将数据字段作为数组而不是对象更明智。然后你可以尝试这样的事情;

List<String> ids = JsonPath.read(json, "$.response.data[*].number.id");
于 2014-07-10T12:13:01.823 回答