2013-07-20 5 views
0

PHP를 사용하여 데이터베이스 쿼리에서 얻은 Json을 생성하고 있습니다. 그 결과는 다음과 같습니다Gson 디코딩 PHP Json

[ 
    { 
     "title":"Title 1", 
     "description":"This is description 1", 
     "add_date":"2013-07-17 10:07:53" 
    },{ 
     "title":"Title 2", 
     "description":"This is description 2", 
     "add_date":"2013-07-17 10:07:53" 
    } 
] 

이 같은 데이터를 분석 할 GSON을 사용하고 있습니다 :

Exception in thread "AWT-EventQueue-0" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3

: 여기
public class Search{ 

    public Search(String text){ 
     try{ 

      // Snipped (gets the data from the website) 

      Gson json = new Gson(); 
      Map<String, Event> events = json.fromJson(resultstring, new TypeToken<Map<String, Event>>(){}.getType()); 

      System.out.print(events.get("description")); 

     }catch(IOException ex){ 
      Logger.getLogger(Search.class.getName()).log(Level.SEVERE, null, ex); 
     } 

    } 
} 

class Event { 
    private String description; 
} 

코드를 실행하는 동안 나는 무엇입니까 메시지입니다

description 또는 title 또는 둘 다 값을 얻으려면 각각 하나씩 반복 할 수 있습니까? 당신이 일을 당신이 잘해야하는지에

답변

2

몇 가지 수정이 이동 : 나는 당신의 bean 클래스를 수정하고 Event의 배열 (변환 어떤 유형을 변경 한

class Event { 
    private String description; 
    private String title; 
    @SerializedName("add_date") private String addDate; 

    public getDescription() { 
     return description; 
    } 
} 


public Search(String text){ 
    try{ 

     // Snipped (gets the data from the website) 

     Gson json = new Gson(); 
     Event[] events = json.fromJson(resultstring, Event[].class); 

     System.out.print(events[0].getDescription()); 

    }catch(IOException ex){ 
     Logger.getLogger(Search.class.getName()).log(Level.SEVERE, null, ex); 
    } 

} 

,이 때문에 어떤 당신은 실제로 PHP 서비스를 받고 있습니다.)

+0

작동하지만이 오류가 발생합니다. '기호를 찾을 수 없습니다. 기호 : class SerialzedName 위치 : class Event'. 또한, 왜 당신은 그것을 serialze합니까? –

+0

@RyanNaddy 이것은 필드 이름과 json 속성의 직접적인 통신을 사용하지 않는다는 것을 나타내는 주석입니다. 그러나 주석을 가져와야합니다. 그리고 그것은 당신이 얻고있는 오류입니다. –