Kotlin使用Gson的TypeToken报错cannot access '<init>' it is 'public /*package*/' in 'TypeToken'

本文介绍了一种使用Gson库将JSON字符串转换为List对象的方法。通过定义TypeToken和使用fromJson方法,可以轻松地将存储在偏好设置中的JSON字符串转换为List&lt;Turns&gt;对象。

解决方案链接

http://www.it1352.com/787528.html

val turnsType = object : TypeToken<List<Turns>>() {}.type
val turns = Gson().fromJson<List<Turns>>(pref.turns, turnsType)
package com.weishitech.sjykqyaowneng.utils; import android.content.Context; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.weishitech.sjykqyaowneng.bean.WindowInfo; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; public class WebViewWindowManager { private static final String PREFS_NAME = "webview_windows"; private static final String KEY_WINDOWS = "windows"; private final List<WindowInfo> windows = new ArrayList<>(); private Context context; // 私有构造函数,防止外部实例化 private WebViewWindowManager() {} // 静态内部类实现单例(线程安全,延迟加载) private static class SingletonHolder { private static final WebViewWindowManager INSTANCE = new WebViewWindowManager(); } public static WebViewWindowManager getInstance() { return SingletonHolder.INSTANCE; } /** * 初始化:在 Application 中调用 setup(context) */ public void setup(Context context) { this.context = context.getApplicationContext(); init(); } /** * 从 SharedPreferences 加载已保存的窗口数据 */ private void init() { if (context == null) return; String json = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) .getString(KEY_WINDOWS, null); if (json != null && !json.isEmpty()) { Gson gson = new Gson(); Type type = new TypeToken<List<WindowInfo>>() {}.getType(); List<WindowInfo> loadedList = gson.fromJson(json, type); if (loadedList != null) { windows.clear(); windows.addAll(loadedList); } } } /** * 获取所有窗口的副本(避免外部修改) */ public List<WindowInfo> getAllWindows() { return new ArrayList<>(windows); // 返回副本 } /** * 添加新窗口,相同 URL 的旧窗口会被移除,新窗口放在首位 */ public void addWindow(WindowInfo info) { if (info == null || info.getUrl() == null) return; // 移除已存在的同 URL 条目 removeWindow(info.getUrl()); windows.add(0, info); // 插入最前 saveToSP(); } /** * 根据 URL 删除窗口 */ public void removeWindow(String url) { if (url == null) return; windows.removeIf(window -> window.getUrl().equals(url)); saveToSP(); } /** * 清空所有窗口 */ public void clear() { windows.clear(); saveToSP(); } /** * 保存到 SharedPreferences */ private void saveToSP() { if (context == null) return; Gson gson = new Gson(); String json = gson.toJson(windows); context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) .edit() .putString(KEY_WINDOWS, json) .apply(); // 异步提交 } } 这个保存后台退出应用数据就没了
最新发布
12-19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值