json - Combining type and field serializers -


let's assume have case class following setup:

case class place(id:java.util.uuid, name:string) 

i can write (working!) serializer type follows:

class placeserializer extends customserializer[place]( format => (         {             case jobject(jfield("id", jstring(s)) :: jfield("name",jstring(x)) :: nil ) =>                 place(uuid.fromstring(s), x)         },         {             case x:place =>                 jobject(                   jfield("id", jstring(x.id.tostring())) ::                    jfield("name", jstring(x.name)) :: nil)         }         )     ) 

but assuming case class has lot more fields, lead me enumerating entire structure of object ast, creating that's verbose encode primitives.

json4s appears have field serializers can act on specific fields, boilerplate methods included transform names , discard fields. these, however, have following signature serialize , deserialize partial functions:

case class fieldserializer[a: manifest](   serializer:   partialfunction[(string, any), option[(string, any)]] = map(),   deserializer: partialfunction[jfield, jfield] = map() ) 

since jfield (the type representes key -> val json) own type , not subclass of jvalue, how can combine these 2 types of serializers encode id key name uuid, while maintaining default handling of other fields (which primitive datatypes).

essentially i'd format chain understands field within place uuid, without having specify ast structure fields defaultformats can handle.

what i'm looking mimic pattern similar jsonencoder , jsondecoder interfaces in python, can use key name value type determine how handle marshalling field.

the trick not write serializer type, type you're using inside (in case java.util.uuid)

then can add serializer toolbox , type using uuid work types using defaultserializer supported fields did:

case object uuidserialiser extends customserializer[uuid](format => (     {       case jstring(s) => uuid.fromstring(s)       case jnull => null     },     {       case x: uuid => jstring(x.tostring)     }   ) )  implicit val json4sformats = serialization.formats(notypehints) + uuidserialiser 

update link the pr

update 2 pr merged, , now, in case of uuid can use:

import org.json4s.ext.javatypesserializers  implicit val json4sformats = serialization.formats(notypehints) ++ javatypesserializers.all 

Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -