GSON throwing “Expected BEGIN_OBJECT but was BEGIN_ARRAY”?

后端 未结 10 789
暖寄归人
暖寄归人 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: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().

提交回复
热议问题