GSON throwing “Expected BEGIN_OBJECT but was BEGIN_ARRAY”?

后端 未结 10 638
暖寄归人
暖寄归人 2020-11-22 01:31

I\'m trying to parse a JSON string like this one

[
   {
      \"updated_at\":\"2012-03-02 21:06:01\",
      \"fetched_at\":\"2012-03-02 21:28:37.728840\",
           


        
10条回答
  •  既然无缘
    2020-11-22 01:44

    The problem is you're telling Gson you have an object of your type. You don't. You have an array of objects of your type. You can't just try and cast the result like that and expect it to magically work ;)

    The User guide for Gson Explains how to deal with this:

    https://github.com/google/gson/blob/master/UserGuide.md

    This will work:

    ChannelSearchEnum[] enums = gson.fromJson(yourJson, ChannelSearchEnum[].class);
    

    But this is better:

    Type collectionType = new TypeToken>(){}.getType();
    Collection enums = gson.fromJson(yourJson, collectionType);
    

提交回复
热议问题