【问题标题】:(De)Serializing objects automatically to a bundle(De) 将对象自动序列化为捆绑包
【发布时间】:2014-12-17 13:54:05
【问题描述】:

我在 Scala 中看到了一些库,它们可以自动(反)序列化任何自动支持成员类型的案例类,例如 JSON

在 Android 世界中,我希望能够使用 Intent 和 Bundle 来实现。

例如,我想生成这个样板代码:

case class Ambitos(idInc: Long, idGrupo: String, ambitos: Map[String, Seq[String]])
    def serialize(b: Bundle) {
        b.putString("grupo", idGrupo)
        b.putLong("inc", idInc)
        b.putStringArray("ambitos", ambitos.keys.toArray)
        ambitos.foreach { case (a, det) ⇒
            b.putStringArray(a, det.toArray)
        }
    }

    def serialize(b: Intent) {
        b.putExtra("grupo", idGrupo)
        b.putExtra("inc", idInc)
        b.putExtra("ambitos", ambitos.keys.toArray)
        ambitos.foreach { case (a, det) ⇒
            b.putExtra(a, det.toArray)
        }
    }
}

object Ambitos {
    def apply(b: Intent): Ambitos =
        Ambitos(b.getLongExtra("inc", -1), b.getStringExtra("grupo"),
            b.getStringArrayExtra("ambitos").map{ a ⇒ (a, b.getStringArrayExtra(a).toSeq) }.toMap)

    def apply(b: Bundle): Ambitos =
        Ambitos(b.getLong("inc"), b.getString("grupo"),
            b.getStringArray("ambitos").map{ a ⇒ (a, b.getStringArray(a).toSeq) }.toMap)
}

是否存在这样的图书馆,还是我必须自己制作?

对于在活动之间传递复杂信息以及处理ActivityonSaveInstanceState()onRestoreInstanceState(),这个工具会很棒。

【问题讨论】:

    标签: android scala serialization deserialization


    【解决方案1】:

    您可以使用 GSON lib 做一些不同的事情,我假设您有一些复杂的对象并且您想从一个活动传递到另一个活动。

    只使用 GSON

    Gson gson = new Gson();     
    // convert java object to JSON format,  
    // and returned as JSON formatted string  
    String jsonString = gson.toJson(complexJavaObj);
    

    然后就用

    i.putExtra("objectKey",jsonString);
    

    并像第二个活动一样阅读

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
    String jsonString = extras.getString("objectKey");
    
     if(jsonString!=null){
       Gson gson = new Gson();
       ComplexJavaObj complexJavaObj= gson.fromJson(jsonString, ComplexJavaObj .class);
      }
    }
    

    希望这会给你一个基本的想法。

    【讨论】:

    • 这是一个简单的替代方法,可以序列化为 JSON,然后将生成的字符串转换为 Bundle。我不确定它是否是性能最好的。
    • 另一个好处是相同的代码用于从/到 Intent 和 Bundle 的序列化。
    【解决方案2】:

    这是尼克在Android Scala forum 中为我提供的答案:

    如果您了解宏的使用方法,这应该相对简单:) Here’s one 序列化对 (key, value)

    从那里,您只需要添加案例类检查位。 Example(有点复杂),用法见第 89 行。 最后一点,我将使它基于类型类而不是基于继承:

    trait Bundleable[A] {
      def toBundle(x: A): Bundle
      def fromBundle(b: Bundle): Try[A]
    }
    
    implicit def genBundleable[A]: Bundleable[A] = macro ???
    
    def bundle[A: Bundleable](x: A) =
      implicitly[Bundleable[A]].toBundle(x)
    

    通过这种方式,您可以手动和自动定义Bundleable[A] 的实例。而且你的数据模型没有被 Android 的废话污染。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-24
      • 2015-03-19
      • 1970-01-01
      • 2013-10-27
      相关资源
      最近更新 更多