2012-09-24 90 views
1

我正在使用mongodb作爲我的android app.Mongodb的雲服務器java庫不能在Android中工作,所以我使用rest api .i編寫了以下代碼以獲取JSON響應,並扔在MyClass的,但它給IllegalStateException異常與無法從Android中的mongodb服務器獲取文檔列表

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_Object at line 1 column 35 

代碼:

   try { HttpGet mRequest = new HttpGet("https://api.mongolab.com/api/1/databases/mydb/collections/mycol?apiKey=myKey");  

        DefaultHttpClient client = new DefaultHttpClient(); 
    try { 
       HttpResponse response = client.execute(mRequest); 

       InputStream source = response.getEntity().getContent(); 

       Reader reader = new InputStreamReader(source); 

       Gson gson = new Gson(); 

      Type typeOfCollectionOfMyObject = new TypeToken<Collection<MYObject>>(){}.getType(); 

      quizDBObjectList = gson.fromJson(reader, typeOfCollectionOfMyObject); 

      } catch (IOException e) { 
      mRequest.abort(); 
      } 

這還不是全部的代碼,但我得到這個block.Any幫助中的例外呢?

MYOBJECT的定義是

  public class MYObject { 

        private long index ; 
        private String question; 
        private String answer; 
        private String optionA; 
        private String optionB; 
        private String optionC; 
        private String optionD; 
        private String createdAt; 
        private String active; 
       //getters and setters of data members 
     } 

和我得到的迴應是:

      [ { "_id" : { "$oid" : "505ab996aded66f4c1ccc7f2"} , "index" : 0 , "question" : "some text ?" , "optiona" : "optionA" , "optionb" : "optionB" , "optionc" : "OptionC" , "optiond" : "optionD" , "answer" : "answer" , "created_at" : { "$date" : "2012-09-20T06:37:04.306Z"} , "Active" : "1"} , { "_id" : { "$oid" : "505ab997aded66f4c1ccc7f3"} , "index" : 1 , ..../objects like that] 

顯然我是不知道的事實,_id會被服務器響應。 你可以給我正確的類定義來將這個json對象放入我的自定義類中。感謝

回答

1

java.lang.IllegalStateException:預期BEGIN_ARRAY但BEGIN_Object在行1列35

這說明了一切,應該有地方[代替{。也許你得到一個單一的對象,而不是一個數組?

以上可能有幫助。爲了獲得更好的回答以下需要:

定義的 MYObject
    • 精確解析字符串

    你可以得到分析的字符串如通過從reader讀入StringBuider或通過使用番石榴的CharStreams.toString(reader)更簡單。

  • +0

    謝謝@maaartinus,我編輯了我的問題,現在它應該給你清晰的畫面。 – RSS

    +0

    我看不出問題,可能除了混淆了'typeOfCollectionOfQuizDBObject'和'typeOfCollectionOfMyObject',但是這可能發生在寫問題的時候。通過上面給出的對象,「BEGIN_ARRAY」預期的唯一位置就是開始,這是滿足的。 – maaartinus

    +0

    兩者都是相同的變量,我只是做了更正。你的意思是,MYObject是正確的,以獲得json對象?我的JSON對象的鍵與我的自定義類的數據成員正確映射。 – RSS

    相關問題