Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala unpickling from string

I tried the following Unit Test.

First test testUnpickleJsonPickleFormat works well. It pickles a String and unpickle the pickle.

testUnpickleString{1,2} tests to unserialize a String. But they don't work at all. I don't know where something miss me.

import org.junit.Test

import scala.pickling._
import scala.pickling.json._

class PicklerTest {

  @Test
  def testUnpickleJsonPickleFormat {
    val src = "elem 1"
    val pckl = src.pickle
    val res = pckl.unpickle[String]
    println(src)
    println(pckl.toString +"\n")
    println(res)
  }

  @Test
  def testUnpickleString1 {
    val json = """JSONPickle({
                 |      "tpe": "java.lang.String",
                 |      "value": "elem 1"
                 |    })""".stripMargin.trim
    val pckl = JSONPickle(json.toString)
    val res = pckl.unpickle[String]

  }

  @Test
  def testUnpickleString2 {
    val src = "elem 1"
    val pckl = src.pickle
    val pckl2 = JSONPickle(pckl.toString)
    val res = pckl2.unpickle[String]
    println(src)
    println(pckl.toString +"\n")
    println(res)
  }
}

I don't know how to use unpickle with the Scala Pickle framework.

like image 238
fsart Avatar asked Mar 21 '23 17:03

fsart


1 Answers

You should use

{
  "tpe": "java.lang.String",
  "value": "elem 1"
}

without JSONPickle(...):

val json = """{
  "tpe": "java.lang.String",
  "value": "elem 1"
}"""

JSONPickle(json).unpickle[String]
// String = elem 1

JSONPickle({...}) is not a valid JSON.

You should also use pckl.value instead of pckl.toString to get JSON without JSONPickle(...):

val src = "elem 1"
val pckl = src.pickle
val pckl2 = JSONPickle(pckl.value)
pckl2.unpickle[String]
// String = elem 1

You could also use pattern matching like this:

val src = "elem 2"
val pckl = src.pickle
val pckl2 = pckl match {
  case JSONPickle(value) => JSONPickle(value)
} 
pckl2.unpickle[String]
// String = elem 2
like image 79
senia Avatar answered Apr 01 '23 21:04

senia