Created
March 13, 2011 14:36
-
-
Save ReSTARTR/868134 to your computer and use it in GitHub Desktop.
string that is serialized by php convert to Map[Any, Any]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PhpSerializer { | |
val patternString = """s:(\d+):\"([^;]*)\";?""".r | |
val patternInt = """i:(\d+);?""".r | |
val patternDouble = """d:(-)?(\d+)(\.\d+)?;?""".r; | |
val patternArray = """a:(\d+):\{(.*)\};?""".r; | |
def parseArray(len: Int, attr: String): Any = { | |
val childs = attr.split(";").toList | |
val len1 = childs.length | |
if (len1 > 1) { | |
var ab = new scala.collection.mutable.ArrayBuffer[Any] | |
var i = 0 | |
val childsLength = childs.length | |
while(i < childsLength) { | |
if (childs(i).startsWith("a:")) { | |
val end = childs.indexOf("}") + 1 | |
val a = Range(i, end).map(childs(_)).mkString(";") | |
ab += de(a) | |
i = end | |
} else { | |
ab += de(childs(i)) | |
i+= 1 | |
} | |
} | |
val abLength = ab.length | |
Range(0, abLength,2).map( ab(_) ).toList.zip( | |
Range(1, abLength,2).map( ab(_) ).toList | |
).toMap[Any, Any] | |
} else { | |
Nil | |
} | |
} | |
def de(ss: String): Any = ss match { | |
case "N;" => null | |
case patternString(len, str) => str | |
case patternInt(i) => i | |
case patternDouble(sign, d1, d2) => sign match { | |
case "-" => (sign + d1 + d2).toDouble | |
case _ => (d1 + d2).toDouble | |
} | |
case patternArray(len, attr) => parseArray(len.toInt, attr) | |
case "O" => null // not implemented | |
case _ => println("unmatch"); ss | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object SerializeTest { | |
def main(args: Array[String]) { | |
val ser = new Serializer | |
List( | |
"i:10;" | |
,"d:1.5;" | |
,"d:42.195;" | |
,"s:1:\"1\";" | |
,"s:2:\"10\";" | |
,"s:3:\"1s1\";" | |
,"s:3:\"へろーわーるど\";" | |
,"N;" | |
,"a:0:{};" | |
,"a:3:{i:0;i:1;i:1;i:2;i:2;i:3;};" | |
,"a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}" | |
,"a:3:{s:1:\"a\";i:1;s:1:\"b\";i:2;s:1:\"c\";i:3;};" | |
,"a:3:{i:0;i:12;i:1;i:13;i:2;i:14;}" | |
,"a:3:{s:9:\"free_word\";s:18:\"ふりーわーど\";s:6:\"madori\";a:3:{i:0;i:12;i:1;i:13;i:2;i:14;};s:12:\"walkminutesh\";i:7;};" | |
).foreach { (s: String) => | |
println("======================") | |
println(s) | |
println(ser.de(s)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment