I am writing a Scala restful API and using SprayJson to parse the JSON that is being passed in during a Post call. For example, we have a JSON structure that looks like this:
{"a", "b", "c", "d", "e", "f", "g", "h"}
Fields a, b, c and h are required but the others are not. I have a custom JSON formatter for my case class. For various reasons, the way I need to structure the case class requires me to do the custom JSON formatter.
Here is a code snippet of my read function in the formatter:
def read(value: JsValue) = {
value.asJsObject.getFields("a", "b", "c", "d", "e", "f", "g", "h")
case Seq(JsString(a),JsString(b),JsString(c),JsString(d),JsString(e),JsString(f),JsString(g),JsString(h))
new Object(a,b,c,d,e,f,g,h)
case _ => throw new DeserializationException("Object expected")
}
How can I implement the above without having numerous case strings matching every possible permutation of fields that may come in?
Im not familiar with spray-json, but if not existed fields are treated as some kind of JNull
then you can try this:
implicit def JsValueToString(v: JsValue): String = v match {
case JsString(s) => s
case _ => null
}
...
case Seq(JsString(a),JsString(b),JsString(c), dOpt, eOpt,fOpt,gOpt,JsString(h)) =>
new Object(a,b,c,dOpt,eOpt,fOpt,gOpt,h)