2

I have the following structure:

    sealed trait BooleanExpression extends Serializable {
        def value: Boolean
    }

    case object True extends BooleanExpression with Serializable {
      val value: Boolean = true
    }

    case object False extends BooleanExpression with Serializable {
      val value: Boolean = false
    }

    case class Not(e: BooleanExpression) extends BooleanExpression with Serializable {
      val value = !e.value
    }

And I'd like to serialize the Not class with the help of Json4s custom serializer (my implementation):

    object NotSerializer extends CustomSerializer[Not](format => ( {
         //deserialize      
         case JObject(
          JField("e", null) ::
            Nil
          ) => Not(null)
        }, {
          //serialize
          case not: Not => JObject(
              JField("not", JBool(not.e.value))
              )
        }))

Main class looks as follows:

object Main extends App {
  implicit val formats: Formats = Serialization.formats(NoTypeHints) + NotSerializer

  val not = Not(Not(Not(False)))

  println(writePretty(not))
}

The class is serialized as follows:

    {
      "not" : true
    }

What I am expecting to see is :

{
  "not" : {
    "not" : {
      "not" : {true}
    }
  }
}

Can't find the bug. What am I doing wrong?

Would be much appreciated for any help.

I have updated the NotSerializerclass - case bE:BooleanExpression part.

Robin Green
  • 32,079
  • 16
  • 104
  • 187
t_sologub
  • 855
  • 2
  • 15
  • 26
  • 1
    Your code doesn't make sense. You're not serializing a boolean, you're serializing a boolean expression. So you shouldn't be casting it to a boolean. Are you sure this is the most recent version of your code? – Robin Green Nov 24 '18 at 17:17
  • @RobinGreen yes, you are right. I have uploaded the latest version of my code. Removed cast to Boolean, but now I am getting another output. I have updated the question – t_sologub Nov 24 '18 at 17:30

1 Answers1

0

Instead of serialising the value, you need to serialise the contained expression. So don't create a JBool - instead, call Extraction.decompose - and don't call .value, because that evaluates the Boolean expression.

Robin Green
  • 32,079
  • 16
  • 104
  • 187