scala - How to enforce strict serialization of JSON in Play 2.x -


play's json serialization default permissive when serializing json case class. example.

case class stuff(name: string, value: option[boolean])

implicit val stuffreads: reads[stuff] = ( ( __ \ 'name).read[string] , ( __ \ 'value).readnullable[boolean] )(stuff.apply _)

if following json received:

{name: "my stuff", value: true, extrafield: "this shouldn't here"}

it succeed 'jssuccess' , discard 'extrafield'.

is there way construct json reads function have return jserror if there 'unhandled' fields?

you can verify object doesn't contain keys before performing own decoding:

import play.api.data.validation.validationerror  def onlyfields(allowed: string*): reads[jsobject] = reads.filter(   validationerror("one or more fields!") )(_.keys.forall(allowed.contains)) 

or if don't care error messages (and one's not helpful, anyway):

def onlyfields(allowed: string*): reads[jsobject] =   reads.verifying(_.keys.forall(allowed.contains)) 

and then:

implicit val stuffreads: reads[stuff] = onlyfields("name", "value") andthen (   (__ \ 'name).read[string] ,   (__ \ 'value).readnullable[boolean] )(stuff) 

the repetition isn't nice, works.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -