2014-09-24 3 views
0

GSon 사용자 가이드를 읽고 여기에 몇 가지 질문을했지만 실제로 GSON으로 Java 개체를 만들려고하면서 오류가 발생하는 이유를 이해하기 위해 애 쓰고 있습니다.Gson to Plain Old Java Object (POJO)

public class TestJSON extends ActionBarActivity { 
    private Location start; 
    private String length; 
    private String url = "http://maps.googleapis.com/maps/api/directions/json?origin="; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_test_json); 

     // dummyprovider is provided by google to let me set a location. 
     start = new Location("dummyprovider"); 
     start.setLatitude(51.5033630); 
     start.setLongitude(-0.1276250); 

     // Recieve an android warning if you run a retrieval task (such as JSON) 
     // in the main thread). 
     try { 
      System.out.println("printing Json"); 

      Thread thread = new Thread(new Runnable() { 
       @Override 
       public void run() { 
        try { 

         toJava(readJsonFromUrl(urlBuilder())); 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 
       } 
      }); 
      thread.start(); 

     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.test_json, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 
     if (id == R.id.action_settings) { 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

    // I think in future I will call this function a ton of times and send it 
    // some locations as waypoints for it to try and get closer to the 
    // distances. 
    private String urlBuilder() { 
     String newUrl = url + start.getLatitude() + "," + start.getLongitude() 
       + "&destination=51.5042178,23"; 

     return newUrl; 
    } 

    // Builds the string for JSON. 
    private String readAll(Reader rd) throws IOException { 
     StringBuilder sb = new StringBuilder(); 
     int cp; 
     while ((cp = rd.read()) != -1) { 
      sb.append((char) cp); 
     } 
     return sb.toString(); 
    } 

    // Take an input url and reads from it using the url above. We then put it 
    // into a JSON object. 
    private JSONObject readJsonFromUrl(String url) throws IOException, 
      JSONException { 
     InputStream is = new URL(url).openStream(); 
     try { 
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, 
        Charset.forName("UTF-8"))); 
      String jsonText = readAll(rd); 
      JSONObject json = new JSONObject(jsonText); 

      return json; 
     } finally { 
      is.close(); 
     } 
    } 

    private void toJava(JSONObject obj) throws Exception { 
     Gson gson = new Gson(); 
     MapsRoute m = gson.fromJson(readJsonFromUrl(urlBuilder()).toString(), 
       MapsRoute.class); 
     System.out.println(m); 

    } 

    } 

MapsRoute.java

public class MapsRoute { 

     @SerializedName("routes") 
     public List<String> routes; 

     @SerializedName("copyrights") 
     public String copyrights; 

     @SerializedName("legs") 
     public List<String> legs; 

     @SerializedName("steps") 
     public List<String> steps; 

    } 

이것은 스택 추적

09-24 19:22:47.367: W/System.err(1720): com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 27 
09-24 19:22:47.367: W/System.err(1720):  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176) 
09-24 19:22:47.367: W/System.err(1720):  at com.google.gson.Gson.fromJson(Gson.java:803) 
09-24 19:22:47.367: W/System.err(1720):  at com.google.gson.Gson.fromJson(Gson.java:768) 
09-24 19:22:47.367: W/System.err(1720):  at com.google.gson.Gson.fromJson(Gson.java:717) 
09-24 19:22:47.367: W/System.err(1720):  at com.google.gson.Gson.fromJson(Gson.java:689) 
09-24 19:22:47.367: W/System.err(1720):  at boyle.matt.runrouter.TestJSON.toJava(TestJSON.java:119) 
09-24 19:22:47.367: W/System.err(1720):  at boyle.matt.runrouter.TestJSON.access$2(TestJSON.java:117) 
09-24 19:22:47.371: W/System.err(1720):  at boyle.matt.runrouter.TestJSON$1.run(TestJSON.java:47) 
09-24 19:22:47.371: W/System.err(1720):  at java.lang.Thread.run(Thread.java:856) 
09-24 19:22:47.371: W/System.err(1720): Caused by: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 27 
09-24 19:22:47.371: W/System.err(1720):  at com.google.gson.stream.JsonReader.nextString(JsonReader.java:821) 
09-24 19:22:47.371: W/System.err(1720):  at com.google.gson.internal.bind.TypeAdapters$13.read(TypeAdapters.java:358) 
09-24 19:22:47.371: W/System.err(1720):  at com.google.gson.internal.bind.TypeAdapters$13.read(TypeAdapters.java:346) 
09-24 19:22:47.371: W/System.err(1720):  at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40) 
09-24 19:22:47.371: W/System.err(1720):  at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:81) 
09-24 19:22:47.371: W/System.err(1720):  at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60) 
09-24 19:22:47.371: W/System.err(1720):  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93) 
09-24 19:22:47.371: W/System.err(1720):  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172) 
09-24 19:22:47.371: W/System.err(1720):  ... 8 more 
입니다

나는 무언가를 잘못 이해하고 있으며지도에 정말로 감사 할 것이라고 확신한다.

이것은 googlemaps URL이며 구문 분석을 시도하고 있습니다. 성공적으로 readfromurl 메소드에서 sys를 사용할 수 있으므로 성공적으로 수신하고 있습니다.

http://maps.googleapis.com/maps/api/directions/json?origin=51.5033630,-0.1276250&destination=51.5042178,23

EDIT :이 readsFromUrl를 호출 출력 (urlBuilder());

09-24 19 : 57 : 03.879 : I/System.out에 (4068) { "상태": "OK", "라우팅": [{ "waypoint_order" [] "요약 "북서쪽": { "lng": 23.0020594, "lat": 52.4304362}} : "A2", "경계선": { "남서": { "lng": - 0.1262498, "lat": 50.91870669999999}, " "다리": [ "기간": { "가치": 63803, "텍스트": "17 시간 43 분}", "거리": { "가치": 1825694, "텍스트": "1,826 km" }, "END_LOCATION": { "LNG": 23.0020594, "위도"51.50389209999999}, "START_ADDRESS": "70 화이트 홀, 런던

SW1A 2AS, 영국", "END_ADDRESS": "Orzechów - 콜로니 아 2, 21-109 Orzechów-Kolonia, 폴란드 ","start_location ": {"lng ": - 0.1262498,"lat ": 51.5034032},"via_waypoint ": [],"steps ": [{"html_instructions ":"Head north </b> Whitehall/Whitehall/A3212 </b> 방면 말 경비원 Ave </b> ","기간 ": {"가치 ": 17,"텍스트 ":"1 분 "},"거리 ": {"value ": 157,"text ":"0.2 km "},"end_location ": {"lng ": - 0.1265332,"lat ": 51.50479920000001},"polyline ": {"points ":"ggjyH "운전": "방향 전환": "주행 모드": "주행 중"), { "html_instructions": "0" { "value": 49, "text": " right </b>을 빅토리아 제방/A3211 </b>min "}"거리 ": {"값 ": 389,"텍스트 ":"0.4 km "},"end_location ": {"lng ": - 0.1239744,"lat ": 51.5011942},"폴리 라인 " { "점": "aojyHp [email protected] En @ ~ @ F @? b @ Bl @@"}, "start_location": { "lng": - 0.1231268, "lat": 51.50464890000001}, "maneuver": "우회전 ","TRAVEL_MODE ":"DRIVING "}, {"html_instructions ":" 돌립니다 </b>을 웨스트 민스터 다리 RD/A302 위에 </b>를 유료 영역을 떠나 </DIV> 수신자 영역을 입력 </DIV> "왼쪽 , "duration": { "value": 62, "text": "1 min"}, "거리": { "값": 507, "텍스트": "0.5 km"}, "end_location": { "lng": - 0.1170572, "lat": 51.50053550000001}, "polyline": { "points": "myiyHxeW @ ABABCB? DADCBABCBC @ CBEBI? K @E @ G @ GBw @@} @@ qA @ q @ DkFFkF? KBMBGBGP [FM "},"start_location ": {"lng ": - 0.1239744,"lat ": 51} KFuAFgAEYC [Ai @?] @ g @@ iA? _ @?Westminster Bridge Rd/A302 </b>에 머무르기 위해 왼쪽으로 돌아 가기 왼쪽으로 돌아 가기 /b> 계속하려면 05011942}, "maneuver": "좌회전", "travel_mode": "DRIVING"}, { "html_instructions" 영역 "012", "기간": { "값": 4, "텍스트": "1 최소"}, "거리": { "값": 26, "텍스트": "26 m"} , "end_location": { "lng": - 0.1167459, "lat": 51.5004276}, "polyline": { "points": "kuiyHrzUFIBEBG @ G @ G @ G? M"}, "start_location": { "lng" : -0.1170572, "lat": 51.50053550000001}, "maneuver": "turn-slight- left", "travel_mode": "DRIVING"}, { "html_instructions": 왼쪽으로 돌아서 </b> Rd/A302 </b> ","duration ": {"value ": 4,"text ":"1 min "},"거리 ": {"값 ": 23,"텍스트 ":"23 m "},"end_loca { "lng": - 0.1167459, "lat": 51.5004276} "{{"lang " 웨스트 민스터 다리에 머물기 위해 오른쪽//right> Rd/A302 </b> "계속 왼쪽", "이동 방향", "여행 모드": "운전 중"}, { "html_instructions" ""{ "value": 10, "text": "1 min"} "거리": { "값": 52, "텍스트": "52 m"} "end_location": { "lng" : -0.1158714, "lat": 51.5007879}, "polyline": { "points": "suiyHhwuea @ GUGQQc @ AE? G? G"}, "start_location": { "lng": - 0.1165272, "lat": 51.5005834 }, "maneuver": "turn-slight-right", "travel_mode": "DRIVING"}, { "html_instructions": " 오른쪽으로 돌아서 </b> 계속해서 Westminster Bridge Rd/A302 </b> 계속 웨스트 민스터 다리를 따라 가십시오 Rd </div> Ente 전화 번호가 zone </div> ","기간 ": {"값 ": 93,"텍스트 ":"2 분 "},"거리 ": {"값 ": 848,"텍스트 ":"0.8 km "},"end_location ": {"lng ": - 0.1051152,"lat ": 51.49874029999999}"폴리 라인 ": {"points ":"} viyHdsU @ EBG @E @ CBEBCFGNQBMFMLYZm @ b @ o @ d @ o @ FUKd @ oAXe @ Vs @ ~ @ iCN [DKFKDGBGJYb @ _B \ mBRiAHa @ BO @I G @ E? G @ UBe @@] CMAOIyAAo @? K? G? EGyAA @ EoAIwCKyCEoAaa @ GiBIc @ CQCW "},"start_location " : { "LNG"- 0.1158714, "위도": 51.5007879}, "기동": "-우회전", "TRAVEL_MODE": "DR

+0

무엇이든 보지 않고 '예상되는 문자열이지만 BEGIN_OBJECT'는 무엇을 의미합니까? –

+0

'readJsonFromUrl()'에서 반환 한'json'을 디버그하여 보여줍니다. 그것은 유효한 JSon 개체가 아닌 것 같습니다. 적어도 파서에는 유효하지 않습니다. – Narmer

+0

@SotiriosDelimanolis는 내가 도움을 청하는 이유가 아닙니다. 검색 문자열은 내 문자열 데이터 구조가 잘못 되었기 때문에 나왔습니다. 다른 예제는 내 설정을 사용하는 것 같습니다. –

답변

0

안녕하세요 JSON과 자바 객체의 매핑이 적절하지 않습니다.

예 : 경로에는 위 코드에서 매핑 된 방식이 아닌 경계, 다리, 저작권, 단계가 있습니다.

+0

올바른 방법에 대한 간단한 개요를 제공해 주시겠습니까? –

+0

Route 클래스, Bound 클래스, Step 클래스, Leg 클래스를 정의합니다. Route 클래스는 Bound 클래스, Step 클래스, String 클래스의 CopyRight, Leg 클래스의 객체를가집니다. 이제 이것을 윤곽선으로 사용하십시오. – pd30

+0

ok 그러면 MapsRoute에 공용 목록 이 있어야하며 경로에 목록 이 있어야합니다. –