简体   繁体   English

使用数组中的JSON Path提取值

[英]Extract value using JSON Path from array

I have Json like this below 我在下面有Json

{"pd":"{\"e\":{\"h\":{\"ak\":\"120\",\"at\":\"app\"},\"b\":[{\"ts\":1319549658547,\"tz\":-400,\"s\":\"StartUpScreen\",\"et\":8,\"ev\":\"sessionStart\",\"si\":\"19477682-de55-414f-82c9-19bec331dc33\",\"tt\":{\"day\":\"Tuesday\"}},{\"ts\":132,\"tz\":-400,\"s\":\"StartUpScreen\",\"et\":3,\"ev\":\"AutomaticFeedRefresh\",\"si\":\"19477682-de55-414f-82c9-19bec331dc33\",\"tt\":{}},{\"ts\":131,\"tz\":-400,\"s\":\"MainScreen\",\"et\":3,\"ev\":\"MainScreen Event\",\"si\":\"19477682-de55-414f-82c9-19bec331dc33\",\"tt\":{}}],\"tt\":{\"OSV\":\"7.10\"}}}","serverPayload":{"httpHeaders":{"x-bluecoat-via":["35D3468EFF4D5F18"],"content-type":["application\/x-www-form-urlencoded"]},"senderIp":["101.100.000.100"]}}

I just need the values of ak , b [ts,si and tt[day]] and senderIp . 我只需要akb [ts,si and tt[day]]senderIp Now I have 2 questions, how do I extract all 'ts' attributes in 'b' and 'senderIp'. 现在我有2个问题,如何在'b'和'senderIp'中提取所有'ts'属性。 I have used the below code for ak, ts and si. 我已经使用下面的代码为ak,ts和si。 I am not sure how I get 'tt', also while I run this code I get an exception like below 我不知道如何得到'tt',同时我运行此代码时会得到如下的异常

    String pd = JsonPath.read(jsonString, "$.pd");
    String ak = JsonPath.read(pd, "$e.h.ak");
    String ak = JsonPath.read(pd, "$e.h.b[0]");
//    String b = JsonPath.read(pd,"$.e.b[0][0]");
//    String b = JsonPath.read(pd,"$.e.b[0][5]");
    System.out.println("value of ak: "+ak);

Exception in thread "main" java.lang.ClassCastException: net.minidev.json.JSONObject cannot be cast to java.lang.String . 线程“main”中的异常java.lang.ClassCastException: net.minidev.json.JSONObject cannot be cast to java.lang.String

$.ehb[0] looks like a JavaScript object (with fields including "ts" and "tz"), not a string. $.ehb[0]看起来像一个JavaScript对象(包含“ts”和“tz”的字段),而不是字符串。 So it's reasonable for your JSON parser to treat it as a JSONObject rather than a string. 因此,您的JSON解析器将其视为JSONObject而不是字符串是合理的。 Probably you need to drill down to $.ehb[0].ts or whatever field you're interested in. Something like this: 可能你需要深入到$.ehb[0].ts或你感兴趣的任何领域。这样的东西:

long ts = JsonPath.read(pd, "$e.h.b[0].ts");

I'm assuming it's your second String ak = line which causes the exception. 我假设它是你的第二个String ak = line导致异常。 I'm having trouble understanding your other question about the "ts" attributes. 我无法理解你关于“ts”属性的其他问题。 Maybe you could format the JSON string for easier reading? 也许您可以格式化JSON字符串以便于阅读?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM