2014-10-22 73 views
0

我已经在Scala中看到过一些库可以自动将任何支持成员类型的案例类自动序列化到JSON(De)将对象自动序列化为一个包

在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(),这个工具非常棒。

回答

-1

这是尼克给我提供了一个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废话所污染。

2

你可以使用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); 
    } 
} 

希望这会给你的基本理念。

+0

这是一个简单的替代方法,将序列化为JSON,然后将结果字符串转换为捆绑包。我不确定,如果这是表现最好的。 – 2014-10-22 07:40:15

+0

另一个好处是,相同的代码用于从/到Intent和Bundle的序列化。 – 2014-10-27 08:16:30