【问题标题】:How convert Object String to Data Class in kotlin如何在kotlin中将对象字符串转换为数据类
【发布时间】:2018-03-29 13:16:29
【问题描述】:

我想把下面的.tostring转换成数据类怎么转换?

InstrumentResponse(AGM=false, AllOrNone=true, Bonus=true, Dividend=true, EGM=false, AuctionDetailInfo=AuctionDetailInfo(AuctionNumber=0, AuctionStatus=0, InitiatorType=0)

我想要做的是通过捆绑从一个片段到另一个片段传递数据类,但使用bundle.putString 做如何再次将其转换为数据类?

有没有更好的方法来实现?或者如何将dataClass.toString 转换为数据类?

【问题讨论】:

    标签: android kotlin gson data-class


    【解决方案1】:

    你应该只使用@Parcelize

    添加

    androidExtensions {
        experimental = true
    }
    

    给你build.gradle

    然后给你的类添加注解

    @Parcelize
    data class InstrumentResponse(...)
    

    然后将值直接放入Bundle

    bundle.putParcelable(key, instrumentReponse)
    

    要检索值,请调用

    val instrumentReponse = bundle.getParcelable<InstrumentResponse>(key)
    

    【讨论】:

    • 如果你必须对类型'Any'和'list or other data class'赋值怎么办
    • Any 不起作用。列表和其他数据类只要是 ParcelableSerializable 就可以工作。
    • 这意味着我必须指定返回类型
    • 但有时我收到 String 或 Int 。如何处理这种情况
    【解决方案2】:

    要在活动之间传递数据类,不要使用 toString。相反,请使用putParcelable。 Parcelable 是 Android 的一种自定义序列化格式。请参阅官方文档(带有示例)here


    如果不想深入了解Parcelable 的实现细节,可以使用kotlin experimental features

    从 Kotlin 1.1.4 开始,Android Extensions 插件提供Parcelable 实现生成器作为实验性功能。

    简而言之,添加

    androidExtensions {
        experimental = true
    }
    

    到您的build.gradle,然后在您的数据类中使用@Parcelize 注释并使其继承自Parcelable

    import kotlinx.android.parcel.Parcelize
    
    @Parcelize
    class InstrumentResponse(...): Parcelable
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      • 2021-10-10
      • 2018-12-08
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多