GSON throwing “Expected BEGIN_OBJECT but was BEGIN_ARRAY”?

后端 未结 10 641
暖寄归人
暖寄归人 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:47

    You need to let Gson know additional type of your response as below

    import com.google.common.reflect.TypeToken;
    import java.lang.reflect.Type;
    
    
    Type collectionType = new TypeToken<List<UserSite>>(){}.getType();
    List<UserSite> userSites  = gson.fromJson( response.getBody() , collectionType);
    
    0 讨论(0)
  • 2020-11-22 01:55

    according to GSON User guide, you cannot.

    Collections Limitations

    Can serialize collection of arbitrary objects but can not deserialize from it. Because there is no way for the user to indicate the type of the resulting object

    0 讨论(0)
  • 2020-11-22 01:58

    I am not sure if this is the best way to use GSON, but works for me. You can use some like this on the MainActivity:

     public void readJson() {
        dataArrayList = new ArrayList<>();
        String json = "[\n" + IOHelper.getData(this) + "\n]\n";
        Log.d(TAG, json);
        try{
            JSONArray channelSearchEnums = new JSONArray(json);
    
            for(int i=0; i< channelSearchEnums.length(); i++)
            {
                JSONObject enum = channelSearchEnums.getJSONObject(i);
                ChannelSearchEnum channel = new ChannelSearchEnum(
                       enum.getString("updated_at"), enum.getString("fetched_at"),
                       enum.getString("description"), enum.getString("language"),
                       enum.getString("title"), enum.getString("url"),
                       enum.getString("icon_url"), enum.getString("logo_url"),
                       enum.getString("id"), enum.getString("modified"))         
    
                       dataArrayList.add(channel);
            }
    
             //The code and place you want to show your data            
    
        }catch (Exception e)
        {
            Log.d(TAG, e.getLocalizedMessage());
        }
    }
    

    You only have strings, but if you would have doubles or int, you could put getDouble or getInt too.

    The method of IOHelper class is the next (Here, the path is save on the internal Storage):

     public static String getData(Context context) {
        try {
            File f = new File(context.getFilesDir().getPath() + "/" + fileName);
            //check whether file exists
            FileInputStream is = new FileInputStream(f);
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            return new String(buffer);
        } catch (IOException e) {
            Log.e("TAG", "Error in Reading: " + e.getLocalizedMessage());
            return null;
        }
    }
    

    If you want more information about this, you can see this video, where I get the code of readJson(); and this thread where I get the code of getData().

    0 讨论(0)
  • 2020-11-22 02:02

    Alternative could be

    to make your response look like

    myCustom_JSONResponse

    {"master":[
       {
          "updated_at":"2012-03-02 21:06:01",
          "fetched_at":"2012-03-02 21:28:37.728840",
          "description":null,
          "language":null,
          "title":"JOHN",
          "url":"http://rus.JOHN.JOHN/rss.php",
          "icon_url":null,
          "logo_url":null,
          "id":"4f4791da203d0c2d76000035",
          "modified":"2012-03-02 23:28:58.840076"
       },
       {
          "updated_at":"2012-03-02 14:07:44",
          "fetched_at":"2012-03-02 21:28:37.033108",
          "description":null,
          "language":null,
          "title":"PETER",
          "url":"http://PETER.PETER.lv/rss.php",
          "icon_url":null,
          "logo_url":null,
          "id":"4f476f61203d0c2d89000253",
          "modified":"2012-03-02 23:28:57.928001"
       }
    ]
    }
    

    instead of

    server_JSONResponse

    [
       {
          "updated_at":"2012-03-02 21:06:01",
          "fetched_at":"2012-03-02 21:28:37.728840",
          "description":null,
          "language":null,
          "title":"JOHN",
          "url":"http://rus.JOHN.JOHN/rss.php",
          "icon_url":null,
          "logo_url":null,
          "id":"4f4791da203d0c2d76000035",
          "modified":"2012-03-02 23:28:58.840076"
       },
       {
          "updated_at":"2012-03-02 14:07:44",
          "fetched_at":"2012-03-02 21:28:37.033108",
          "description":null,
          "language":null,
          "title":"PETER",
          "url":"http://PETER.PETER.lv/rss.php",
          "icon_url":null,
          "logo_url":null,
          "id":"4f476f61203d0c2d89000253",
          "modified":"2012-03-02 23:28:57.928001"
       }
    ]
    

    CODE

      String server_JSONResponse =.... // the string in which you are getting your JSON Response after hitting URL
    String myCustom_JSONResponse="";// in which we will keep our response after adding object element to it
         MyClass apiResponse = new MyClass();
    
         myCustom_JSONResponse="{\"master\":"+server_JSONResponse+"}";
    
    
    
        apiResponse = gson.fromJson(myCustom_JSONResponse, MyClass .class);
    

    After this it will be just any other GSON Parsing

    0 讨论(0)
提交回复
热议问题