WorkManager Data.Builder does not support Parcelable

前端 未结 6 1079
心在旅途
心在旅途 2021-02-20 06:18

When you have a big POJO with loads of variables (Booleans, Int, Strings) and you want to use the new Work Manager to start a job. You then create a Data file which gets added t

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-20 07:04

    In Kotlin, thats how I do it

    Object to Json

    inline fun Any.convertToJsonString():String{
     return Gson().toJson(this)?:""
    }
    

    To Convert back to model,

    inline fun  JSONObject.toModel(): T? = this.run {
      try {
        Gson().fromJson(this.toString(), T::class.java)
      }
        catch (e:java.lang.Exception){ e.printStackTrace()
        Log.e("JSONObject to model",  e.message.toString() )
    
        null }
    }
    
    
    inline fun  String.toModel(): T? = this.run {
      try {
        JSONObject(this).toModel()
       }
       catch (e:java.lang.Exception){
        Log.e("String to model",  e.message.toString() )
    
        null
     }
    }
    

提交回复
热议问题