2016-05-28 8 views
1

を解析し、私の文字列データである:使用Gsonは、私は、文字列を流れる解析するGsonを使用しますが、私はexeption.Hereを取得するには、次の文字列

[ 
    { 
    "source": "Gank.io #145 (2015-12-24)", 
    "title": "view", 
    "url": "https://github.com/florent37/ViewAnimator" 
    }, 
    { 
    "source": "Gank.io #42 (2015-07-23)", 
    "title": "android", 
    "url": "https://github.com/kevinzhow/NaughtyImageView" 
    }, 
    { 
    "source": "Gank.io #28 (2015-07-02)", 
    "title": "iOS UIView", 
    "url": "http://www.devtalking.com/articles/uiview-spring-animation/" 
    } 

] 

私は、文字列の上に解析するために流れるのコードを使用します。

Gson gson = new Gson(); 
SearchResultData searchResultData = gson.fromJson(json,SearchResultData.class); 
List<SearchResult> searchResults = searchResultData.getResults(); 

私の例外は次のとおりです。

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

javaコードを表示します。 –

+0

ここに 'SearchResultData'を投稿してください。 – Ironman

+0

'public class SearchResultData { プライベートリスト結果; 公開リスト getResults(){ 戻り値; } パブリックvoid setResults(List results){ this.results = results; } } ' – CoXier

答えて

1

は、次のことを試してみてください、それが役に立てば幸い!

class SearchResultData { 
    String source; 
    String title; 
    String url; 
} 

... 

private final List<SearchResultData> dataList= new ArrayList<>(); 
... 
Gson gson = new Gson(); 
SearchResultData[] data= gson.fromJson(jsonString, SearchResultData[].class); 
Collections.addAll(dataList, data); 
+1

ありがとうございます – CoXier

1

SearchResultDataは通常、それを解析するタイプの配列またはリストのフィールドを含める必要があります。

別の提案 - そのような方法でそれを行う:

のSearchResultEntryはPOJOクラス含むソース、タイトルとURL文字列である
List<SearchResultEntry> searchResultData = gson.fromJson(json,SearchResultEntry.class); 

エラー

Expected BEGIN_OBJECT but was BEGIN_ARRAY 

はSearchResultDataが

{ 
    "source": "Gank.io #145 (2015-12-24)", 
    "title": "view", 
    "url": "https://github.com/florent37/ViewAnimator" 
} 

としてオブジェクトを期待していることを示していますが、Gsonは、そのようなオブジェクトの配列を発見しました。

あなたの解明によると、これは正しいJSON構造である:

{ 
    "results" : [ 
     { 
     "source": "Gank.io #145 (2015-12-24)", 
     "title": "view", 
     "url": "https://github.com/florent37/ViewAnimator" 
     }, 
     { 
     "source": "Gank.io #42 (2015-07-23)", 
     "title": "android", 
     "url": "https://github.com/kevinzhow/NaughtyImageView" 
     }, 
     { 
     "source": "Gank.io #28 (2015-07-02)", 
     "title": "iOS UIView", 
     "url": "http://www.devtalking.com/articles/uiview-spring-animation/" 
     } 

    ] 
} 
+0

あなたは正しいですが、上記の答えを使用することにしました。お気軽に – CoXier

関連する問題