2016-09-12 75 views
4

我試圖通過廣播在Intent中傳遞包含Analytics報告數據的對象。問題是反序列化返回LinkedTreeMap而不是原始的序列化對象,導致ClassCastException異常。 我試圖遵循所有在這裏找到的答案,從使用TypeToken來修改ProGuard規則,沒有任何工作。Gson的Google Analytics反序列化正在返回LinkedTreeMap

我想實現Parcelable接口,但問題是我有一個內部私人AsyncTask類,其中的數據被收集並推送到將通過廣播發送的意圖。

這裏就是數據序列化的輔助代碼:

public class AnalyticsHelper 
{ 
    ... 

    private class GoogleBatchTask extends AsyncTask<GetReportsRequest,Void,GetReportsResponse> 
    { 
     @Override 
     protected GetReportsResponse doInBackground(@NonNull GetReportsRequest... reports) 
     { 
      GetReportsResponse response = null; 

      try { 
       if (m_reports == null) 
        return null; 
       response = m_reports.reports().batchGet(reports[0]).execute(); 
      } catch (IOException e) { 
       Console.log(e); 
      } 

      return response; 
     } 

     @Override 
     protected void onPostExecute(GetReportsResponse response) 
     { 
      Intent intent = new Intent(); 
      intent.setAction("com.keyone.contactpackapp.ANALYTICS_DATA"); 
      intent.putExtra("response", new Gson().toJson(response)); 

      Context context = PackConfig.instance().context(); 
      if (context == null) 
       return; 

      context.sendBroadcast(intent); 
     } 
    } 
} 

AnalyticsFragment.java,其中反序列化發生了:

public class AnalyticsFragment extends Fragment 
{ 
    @Override 
    public void onResume() 
    { 
     super.onResume(); 

     // Listen to custom intent with data 
     IntentFilter filter = new IntentFilter("com.keyone.contactpackapp.ANALYTICS_DATA"); 

     m_receiver = new BroadcastReceiver() { 
      @Override 
      public void onReceive(Context context, Intent intent) 
      { 
       // Get data from intent and pass it to the right fragment 
       String szJson = intent.getStringExtra("response"); 

       //m_response = new Gson().fromJson(szJson, GetReportsResponse.class); 
       Type listType = new TypeToken<GetReportsResponse>(){}.getType(); 
       m_response = new Gson().fromJson(szJson, listType); 

       Fragment fragment = m_activity.currentFragment(); 
       fragment.updateData(); 
      } 
     }; 

     if (m_activity != null) 
      m_activity.registerReceiver(m_receiver, filter); 
    } 
} 

回答

0

有沒有辦法來反序列化對象以正確的方式由於要序列化的對象的性質,使用Gson既不使用Java Serializable接口,也不使用Android Parcelable接口。

所以我選擇了調用接收者類的實例並通過其中的方法傳遞對象數據