2017-10-30 1 views
0

クラウドエンドポイントで新しくなった。 Cloud EndPointsでGoogle Map APIを使用して地理情報を取得しています。私はJSON Stringにデコードする必要があります国名、administrator_area_level_1、およびadministrator_area_level_2JavaクラウドエンドポイントでのJSON文字列のデコード

ここは私のコードです。

EndPoints.java

@ApiMethod(name = "getLocation", path = "getLocation") 
public StringResponse getlocation(@Named("location") String location) { 
    GeoLocation geoLocation = new GeoLocation(); 
     geoLocation.getCounty(); 
     geoLocation.getAreaLevel1(); 
     geoLocation.getAreaLevel2(); 
    // do some other staff with these values 
    return new StringResponse(// some args); 
} 

GeoLocation.java

public class GeoLocation { 

    String out = ""; 

    public GeoLocation() { 

     try { 
      URL url = new URL(
        "http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true"); 
      // making connection 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setRequestMethod("GET"); 
      conn.setRequestProperty("Accept", "application/json"); 
      if (conn.getResponseCode() != 200) { 
       throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); 
      } 

      // Reading data's from url 
      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); 

      String output; 
      System.out.println("Output from Server .... \n"); 
      while ((output = br.readLine()) != null) { 
       // System.out.println(output); 
       out += output; 
      } 

      // How can I decode JSON String(out) 

      conn.disconnect(); 
     } catch (MalformedURLException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 

    public String getOut() { 
     return out; 
    } 

} 

私はすでに私はこの1つを使用するか、任意の直接的な方法があることができ、GsonライブラリとAndroidので働いていましたそれをデコードするには?または他のより良い方法?そして何dependency私は追加する必要がありますpom.xml私はmavenを使用しています。

答えて

1

あなたはこのgson依存性をthis linkを参照するか、または同じ最新バージョンを使用することができます。

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> 
<dependency> 
    <groupId>com.google.code.gson</groupId> 
    <artifactId>gson</artifactId> 
    <version>2.8.2</version> 
</dependency> 

と同じthis postを使用します。

Gson gson = new Gson(); 
YourClass object = gson.fromJson(yourJson, YourClass.class); 
関連する問題