代码之家  ›  专栏  ›  技术社区  ›  Rupesh

如何在kotlin中将对象字符串转换为数据类

  •  1
  • Rupesh  · 技术社区  · 8 年前

    我想在下面转换。tostring到数据类如何转换?

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

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

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

    2 回复  |  直到 8 年前
        1
  •  1
  •   Kirill Rakhman    8 年前

    你应该使用 @Parcelize

    添加

    androidExtensions {
        experimental = true
    }
    

    给你 build.gradle

    然后将注释添加到类中

    @Parcelize
    data class InstrumentResponse(...)
    

    然后将值直接放入 Bundle

    bundle.putParcelable(key, instrumentReponse)
    

    要检索该值,请调用

    val instrumentReponse = bundle.getParcelable<InstrumentResponse>(key)
    
        2
  •  0
  •   Derlin    8 年前

    要在活动之间传递数据类, 不要使用toString 。相反,使用 putParcelable 。parcelable是Android的自定义序列化格式。见官方文件(附示例) here


    如果你不想深入研究 Parcelable 实现详细信息,您可以使用kotlin experimental features

    从Kotlin 1.1.4开始,Android扩展插件提供 可包裹的 作为实验特性的实现生成器。

    简而言之,添加

    androidExtensions {
        experimental = true
    }
    

    到您的 build.gradle ,然后使用 @Parcelize 并使其继承自 可包裹的 :

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