Google 使用 Gson 的分析反序列化正在返回 LinkedTreeMap

Google Analytics deserialization with Gson is returning LinkedTreeMap

我正在尝试通过广播在 Intent 中传递包含 Analytics Reporting 数据的对象。问题是 returns 一个 LinkedTreeMap 而不是原始序列化对象的反序列化,导致 ClassCastException 崩溃。 我试图遵循在 SO 上找到的所有答案,从使用 TypeToken 修改 ProGuard 规则但没有任何效果。

我想实现 Parcelable 接口,但问题是我有一个内部私有 AsyncTask class,其中收集数据并将其推送到将通过广播发送的意图中。

这是序列化数据的助手代码:

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

由于要序列化的对象的性质,无法使用 Gson 以正确的方式反序列化对象,既不使用 Java Serializable 接口也不使用 Android Parcelable 接口。

所以我选择调用接收者的实例class并通过其中的方法传递对象数据