如何从Java中从GoogleDistanceMatrix API收到的JSON中提取嵌套值?

时间:2017-12-05 11:28:14

标签: java json api distance google-distancematrix-api

尝试将以下JSON返回解析为java可用代码:

{
   "destination_addresses" : [ "New York, NY, USA" ],
   "origin_addresses" : [ "Washington, DC, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "225 mi",
                  "value" : 361951
               },
               "duration" : {
                  "text" : "3 hours 51 mins",
                  "value" : 13876
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}


      // Parse the whole JSON result.
      JSONObject o1 =(JSONObject)JSONValue.parse(outputString);

      JSONArray a1 = (JSONArray) o1.get("rows");//2
      for (int i = 0; i < a1.size(); i++) {
          JSONObject o2 = (JSONObject) a1.get(i);//3
          JSONArray a2 = (JSONArray) o2.get("elements");//4
          for (int j = 0; j < a2.size(); j++) {
              JSONObject o3 = (JSONObject) a2.get(j);//3
              JSONArray a3 = (JSONArray) o3.get("distance");//4
              for(int k =0; k < a3.size(); k++) {
              System.out.println(((JSONObject) a3.get(k)).get(
                      "text").toString());//5
              }

          }

      }

我想访问距离文字值以及文字 持续时间的值。我找到了访问距离和持续时间的代码,但是当我按照旧的示例添加第三个for循环时,我得到了这个预期

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray

在这一行:

   JSONArray a3 = (JSONArray) o3.get("distance");//4

有关其他方式的帮助或建议吗?感谢

2 个答案:

答案 0 :(得分:0)

使用JSONObject,因为它不是数组

private async void button1_Click(object sender, EventArgs e)
{
    Console.WriteLine("about to start task");
    var t = Test();
    Console.WriteLine("task started");
    await t;
    Console.WriteLine("task finished");
}

然后

JSONObject a3 = (JSONObject) o3.get("distance");

答案 1 :(得分:0)

在@sasikumar的帮助下

JSONObject a3 = (JSONObject) o3.get("distance");
String text = null;
text= (String) a3.get("text");
value=(String )a4.get("text");

这解决了我。