android – 使用Gson的Google Analytics反序列化返回LinkedTreeMap
作者:互联网
我正在尝试通过广播在Intent中传递包含Analytics Reporting数据的对象.问题是反序列化返回LinkedTreeMap而不是原始的序列化对象,导致ClassCastException崩溃.
我尝试按照SO上的所有答案,使用TypeToken修改ProGuard规则,但没有任何效果.
我想实现Parcelable接口,但问题是我有一个内部私有AsyncTask类,其中收集数据并将其推送到将通过广播发送的intent中.
以下是数据序列化的帮助程序代码:
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接口,无法以正确的方式反序列化对象.
所以我选择调用一个收件人类的实例,并通过其中的方法传递对象数据
标签:android,gson,google-analytics,google-analytics-api 来源: https://codeday.me/bug/20190711/1429824.html