开发者

Trying to get the value of an element or itself inside some element in Json returns null

开发者 https://www.devze.com 2023-01-30 10:11 出处:网络
Hello Im trying to get the value of an element from a JsonObject. i\'m using java with the Gson library.

Hello Im trying to get the value of an element from a JsonObject. i'm using java with the Gson library.

here is the related part of the code:

String s = "http://maps.googleapis.com/maps/api/directions/json?origin=30.065634,31.209473&destination=29.984177,31.440052&sensor=false";
URL url = new URL(s);

BufferedReader r = new BufferedReader(new InputStreamReader(
    ((HttpURLConnection) url.openConnection()).getInputStream()));

JsonStreamParser jsp = new JsonStreamParser(r);

JsonParser jp = new JsonParser();

JsonElement jsonElement =  jp.parse(r);

JsonObject jsonObject = jsonElement.getAsJsonObject();

System.out.println(jsonObject.get("summary"));

here is a part of the Json:

"status": "OK",   "routes": [ {
    "summary": "Mehwar Al Moneeb",
    "legs": [ {
      "steps": [ {
        "travel_mode": "DRIVING",
        "start_location": {
          "lat": 30.0655100,
          "lng": 31.2096600
        },
        "end_location": {
          "lat": 30.0654400,
          "lng": 31.2096000
        },
        "polyline": {
          "points": "mdovDksn}DLJ",
          "levels": "BB"
        },
        "duration": {
          "value": 1,
          "text": "1 min"
        },
        "html_instructions": "Head \u003cb\u003esouthwest\u003c/b\u003e on \u003cb\u003eOmar Toson\u003c/b\u003e toward \u003cb\u003eMohammed Roshdi\u003c/b\u003e",
        "distance": {
          "value": 9,
          "text": "9 m"
        }
     开发者_运维技巧 }

When I get the top element "routes" its fine and printing it displays what inside the element but when I try to for example to get the element "summary" as shown, the return is null, thats whats is displayed in the output, so subsequently I cannot get the value of it. Whats wrong? how can get the value of any JsonElement? Please reply back to me as soon as you can. Thanks in advance.


Routes is a javascript array. Summary is a property of the first object in that array, so you need to use jsonObject.getAsJsonArray("routes").get(0).get("summary"); or equivalent. I haven't worked with your Java library, but the JS code would be jsonObject.routes[0].summary

Edit: Looked up GSON Documentation and updated code.

0

精彩评论

暂无评论...
验证码 换一张
取 消