2015-04-16 22 views
1

我想用一些json的復古適合,但不能看到我的json字符串有什麼問題,我不斷收到相同的錯誤。我的JSON輸出有什麼問題? retrofit.converter.ConversionException

我在期待一個單詞對象的列表,但我錯過了什麼?有任何想法嗎?

retrofit.converter.ConversionException: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

JSON:

{ 
    "words": [ 
     { 
      "id": "1", 
      "word": "submarine", 
      "word_syllables": "sub-mar-ine", 
      "picture": "none.jpg", 
      "picture_dir": "", 
      "soundfile": "", 
      "user_id": "1", 
      "created": "2015-04-08 16:32:07", 
      "modified": "0000-00-00 00:00:00" 
     }, 
     { 
      "id": "2", 
      "word": "computer", 
      "word_syllables": "com-pute-r", 
      "picture": "computer.jpg", 
      "picture_dir": "", 
      "soundfile": "", 
      "user_id": "0", 
      "created": "2015-04-08 16:32:07", 
      "modified": "0000-00-00 00:00:00" 
     } 
    ] 
} 

改造的Android代碼:

private void requestData(){ 

    RestAdapter adapter=new RestAdapter.Builder() 
    .setEndpoint(ENDPOINT) 
    .build(); 

    WordsAPI api=adapter.create(WordsAPI.class); 

    api.getRestWordFeed(new Callback<List<Word>>(){ 

      @Override 
      public void failure(RetrofitError arg0) { 
       // TODO Auto-generated method stub 
       Log.v("error",arg0.getMessage()); 
      } 

      @Override 
      public void success(List arg0, Response arg1) { 
       // TODO Auto-generated method stub 
       wordList=arg0; 
       printList();      
      } 
    }); 

} 

API接口:

package com.example.testretrofitlib; 

import java.util.List; 

import retrofit.Callback; 
import retrofit.http.GET; 

public interface WordsAPI { 

    @GET("/rest_words/index.json") 
    public void getRestWordFeed(Callback<List<Word>> response); 


} 
+0

你期待一個列表但JSON有一個物品詞已經在它的陣列。 – kmcnamee

回答

2

該JSON的單詞對象列表嵌入具有「words」屬性的對象的值內。這個錯誤只是指出,它期望一個數組分隔符[,而不是它找到該對象的開始。

您可以修復JSON(刪除{"words": <ACTUAL_ARRAY> }並僅保留包含兩個元素的數組)或修改您在getRestWordFeed中期望的數據結構。

3

您的JSON是一個對象,它具有一個屬性:「單詞」,它是一個單詞對象數組。你的錯誤:「期望的BEGIN_ARRAY,但是BEGIN_OBJECT」表示你正在等待一個數組,但返回了一個對象。一個解決辦法是返回以下爲JSON:

[ 
    { 
     "id": "1", 
     "word": "submarine", 
     "word_syllables": "sub-mar-ine", 
     "picture": "none.jpg", 
     "picture_dir": "", 
     "soundfile": "", 
     "user_id": "1", 
     "created": "2015-04-08 16:32:07", 
     "modified": "0000-00-00 00:00:00" 
    }, 
    { 
     "id": "2", 
     "word": "computer", 
     "word_syllables": "com-pute-r", 
     "picture": "computer.jpg", 
     "picture_dir": "", 
     "soundfile": "", 
     "user_id": "0", 
     "created": "2015-04-08 16:32:07", 
     "modified": "0000-00-00 00:00:00" 
    } 
]