package com.example.base.extensions

import android.os.Bundle
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken


/**
 * intent 传object 数据
 */
fun Bundle.putObject(any: Any?) {
    any ?: return
    this.putString(any::class.java.simpleName, Gson().toJson(any))
}

inline fun <reified T> Bundle.getObject(): T? {
    return try {
        Gson().fromJson(this.getString(T::class.java.simpleName), T::class.java)
    } catch (e: Exception) {
        null
    }
}

/**
 * intent 传list 数据
 */
inline fun <reified T> Bundle.putList(list: List<T>?) {
    this.putString("list${T::class.java.simpleName}", Gson().toJson(list))
}


inline fun <reified T> Bundle.getList(): List<T> {
    return try {
        val str = this.getString("list${T::class.java.simpleName}")
        Gson().fromJson(str, object : TypeToken<List<T>?>() {}.type)
    } catch (e: java.lang.Exception) {
        emptyList()
    }

}