2014-10-22 37 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

相關問題