2017-07-18 117 views
0

請幫助,這是我第一次使用JSON/GSON。 我從Google地理編碼API獲取了此JSON數據,但無法弄清楚如何從中提取「formatted_address」。在java中使用GSON從JSON中提取數據

{ 
    "results" : [ 
     { 
     "address_components" : [ 
      { 
       "long_name" : "Google Building 41", 
       "short_name" : "Google Bldg 41", 
       "types" : [ "premise" ] 
      }, 
      { 
       "long_name" : "1600", 
       "short_name" : "1600", 
       "types" : [ "street_number" ] 
      }, 
      { 
       "long_name" : "Amphitheatre Parkway", 
       "short_name" : "Amphitheatre Pkwy", 
       "types" : [ "route" ] 
      }, 
      { 
       "long_name" : "Mountain View", 
       "short_name" : "Mountain View", 
       "types" : [ "locality", "political" ] 
      }, 
      { 
       "long_name" : "Santa Clara County", 
       "short_name" : "Santa Clara County", 
       "types" : [ "administrative_area_level_2", "political" ] 
      }, 
      { 
       "long_name" : "California", 
       "short_name" : "CA", 
       "types" : [ "administrative_area_level_1", "political" ] 
      }, 
      { 
       "long_name" : "United States", 
       "short_name" : "US", 
       "types" : [ "country", "political" ] 
      }, 
      { 
       "long_name" : "94043", 
       "short_name" : "94043", 
       "types" : [ "postal_code" ] 
      } 
     ], 
     "formatted_address" : "Google Bldg 41, 1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA", 
     "geometry" : { 
      "bounds" : { 
       "northeast" : { 
        "lat" : 37.4228642, 
        "lng" : -122.0851557 
       }, 
       "southwest" : { 
        "lat" : 37.4221145, 
        "lng" : -122.0859841 
       } 
      }, 
      "location" : { 
       "lat" : 37.4224082, 
       "lng" : -122.0856086 
      }, 
      "location_type" : "ROOFTOP", 
      "viewport" : { 
       "northeast" : { 
        "lat" : 37.4238383302915, 
        "lng" : -122.0842209197085 
       }, 
       "southwest" : { 
        "lat" : 37.4211403697085, 
        "lng" : -122.0869188802915 
       } 
      } 
     }, 
     "place_id" : "ChIJxQvW8wK6j4AR3ukttGy3w2s", 
     "types" : [ "premise" ] 
     } 
    ], 
    "status" : "OK" 
} 

這是我做過嘗試,但它拋出IndexOutOfBoundsException異常:

public String getLocationData(String location) { 

     try { 

      URL url = new URL(location); 
      HttpURLConnection request = (HttpURLConnection) url.openConnection(); 
      request.connect(); 

      JsonParser parser = new JsonParser(); 
      JsonElement content = parser.parse(new InputStreamReader((InputStream) request.getContent())); 
      JsonObject jObject = content.getAsJsonObject(); 
      JsonArray jArray = jObject.getAsJsonArray("results"); 
      jObject = jArray.get(1).getAsJsonObject(); 

      String result = jObject.getAsString(); 

      return result; 

     } catch (MalformedURLException ex) { 
      ex.printStackTrace(); 

     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
     return "fail"; 
    } 
+0

可以創建對應於上述JSON響應一個豆,然後解析到一個Java bean上述響應。 –

+0

當你想解決一個異常時,建議包含它的堆棧跟蹤,這樣我們可以很容易地檢查錯誤發生的位置以及在哪個上下文中,而不必讀取整個代碼並猜測錯誤是什麼。 – Aaron

+0

在這種情況下,它看起來像'results'數組只包含一個元素,這就解釋了爲什麼調用'get(1)'會失敗。我想你想寫'get(0)'(Java中的數組是0-索引) – Aaron

回答

0

我只能妄自猜測,你的眼前是什麼錯誤沒有一個堆棧跟蹤,但你試圖訪問只包含一個項目數組的第二個項目:

  • results陣列包含一個元素(一個對象,其字段是address_components陣列,formatted_addressgeometryplace_idtypes

  • 你想用jArray.get(1)(數組訪問它的第二個元素是用Java 0索引)

這是IndexOutOfBoundsException的典型原因。

您可能想要訪問jArray.get(0)的唯一項目,您可以將其作爲JsonObject進行操作,其字段可以訪問。

+0

我正在嘗試訪問formatted_address。我認爲這是結果數組的第二個元素,但顯然不是。這是我第一次使用JSON,我不知道我做錯了什麼。 –

+0

@GoranKovač你已經有一個數組,其中包含一個具有多個字段的對象,例如'formatted_address'。你所做的錯誤的是試圖從數組中訪問這個'formatted_address'字段,而你應該從數組中檢索對象,然後從對象中檢索字段的值。 – Aaron

+0

@GoranKovač這是你似乎沒有得到的'[{「field」:「value」}]'和'{「field」:「value」}'之間的區別。在第二種情況下,您可以直接從對象中獲取字段,但首先必須從數組中提取對象並使用該對象來獲取字段。你不會操縱'JsonArray':它有元素而不是字段,它可能是原始值或對象,但肯定不是鍵/值對 – Aaron

0

你寫jObject = jArray.get(1).getAsJsonObject();,但您的陣列只包含一個元素。請記住,Java中的數組是0索引。您應該使用jObject = jArray.get(0).getAsJsonObject();

+0

我知道它是0索引的。我試圖從「結果」數組訪問「formatted_address」。我不明白爲什麼「結果」只有1個元素時,它應該有5個。 –

+0

@GoranKovač因爲一個對象是有意義的,不應該被抽象出來。如果數組中有兩個對象呢?你應該通過獲取數組的第六項來訪問第二個對象的'formatted_address'?如果總是有這5個字段的單個對象,那麼它應該被刪除的數組,而不是對象 – Aaron

+0

@GoranKovač你應該添加一些'Sysout'(甚至更好,使用調試器)並檢查你的不同的值元素('JSONElement','JSONObject','JSONArray'),並且您將立即瞭解發生了什麼 – Nathan

0
//URL url = new URL("http://localhost:7001/JMR_SERVICE/services/CalSerice?wsdl"); 

URL endPointUrl= new URL("http://192.168.0.161:7200/JMR_SERVICE/services/CalSerice?wsdl"); 

org.apache.axis.client.Service service=new org.apache.axis.client.Service(); 


CalSericeSoapBindingStub stub=new CalSericeSoapBindingStub(endPointUrl,service); 

String msg=stub.hello("hello how are you..............?"); 
String resp=stub.getID("ADMINUSER4"); 
+0

用肥皂調用服務器端服務非常簡單..如果你需要請把它拿起來,然後複製它,它工作的很好。 –

-1
public class Dao {   
    String result=""; 
    public String getDetails(int empid) 
    { 
     try { 
      Class.forName("oracle.jdbc.driver.OracleDriver"); 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
     } 
     Connection con = null; 
     try { 
      con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","om"); 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
     System.out.println("connected data base"); 

     try 
     { 
      //stmt.execute("create table com (sno int,name varchar(90),age int)"); 
      System.out.println("connection is established"); 
     } 
     catch(Exception ex) 
     { 
      ex.printStackTrace(); 
     } 
     try 
     { 
      PreparedStatement psmt=con.prepareStatement("select name from emp122 where id=id"); 
      //psmt.setInt(2,id); 

      String query="select name from emp120 where id='emid'"; 
      ResultSet rs=psmt.executeQuery(); 
      //String result=""; 
      while(rs.next()) 
      { 
       result=rs.getString(1); 
      } 
      System.out.println(result); 

     } 
     catch(Exception ex) 
     { 
      ex.printStackTrace(); 
      return "Not Record found"; 
     } 


     return result; 

    } 

    public ArrayList<String[]> getconnection(String id)throws ClassNotFoundException, SQLException 
    { 
     System.out.println("collection jdbc"); 
     ArrayList ls=new ArrayList(); 

     Class.forName("oracle.jdbc.driver.OracleDriver"); 
     Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.92:1521:FCARB01","EODMS","eodms"); 
     System.out.println("connected data base"); 
     Statement stmt=con.createStatement(); 
     String sql="select QRY_TEXT from EOD_QRY_EXEC_LOG where OPERATOR_ID ='"+id+"'"; 
     System.out.println("fetching value...."); 
     ResultSet rs=stmt.executeQuery(sql); 

     System.out.println("resulsetmetadata"); 
     ResultSetMetaData rsmd=rs.getMetaData(); 
     int a=rsmd.getColumnCount(); 
     while(rs.next()) 
     { 
      for(int i=1;i<=a;i++) 
      { 
       ls.add(rs.getString(i)); 
      } 
     } 

     return ls; 
    } 
} 
+0

你確定你正在回答正確的問題嗎?它與數據庫有什麼關係? – Aaron