使用Gson解析后跟字符串

时间:2016-05-28 09:02:48

标签: java android 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 $

2 个答案:

答案 0 :(得分:0)

SearchResultData应包含Array或List类型的字段以正常解析它。

另一个建议 - 以这种方式做到:

List<SearchResultEntry> searchResultData = gson.fromJson(json,SearchResultEntry.class);

其中SearchResultEntry是包含source,title和url字符串的POJO类。

错误

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/"
      }

    ]
}

答案 1 :(得分:0)

尝试以下操作,希望有所帮助!

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);