How to partially parse a json string into my case class with spray json?

1,896 views
Skip to first unread message

Leon Ma

unread,
Feb 25, 2014, 3:59:29 AM2/25/14
to spray...@googlegroups.com
input like this:

{
    "name" : "leon",
     "address" : "my address",
     "unknowfield1" : "blabla",
      "unknowfield2" : "blabla",

}

case class Info(name:String, address:String)

val myObject = jsonAst.convertTo[Info]

Anyone can provide some code snippet to do this?


Thanks





Johannes Rudolph

unread,
Feb 25, 2014, 4:05:08 AM2/25/14
to spray...@googlegroups.com
Hi Leon,

spray-json just ignores fields that are not mapped. So, nothing
special to do here. It may suffice to provide an

implicit val infoFormat = jsonFormat2(Info)

to get it working.

Johannes

-----------------------------------------------
Johannes Rudolph
http://virtual-void.net

Leon Ma

unread,
Feb 25, 2014, 4:22:49 AM2/25/14
to spray...@googlegroups.com, johannes...@googlemail.com
cool, I just tried and it works!

But if the json is like this

{

     "address" : "my address",
     "unknowfield1" : "blabla",


}

case class Info(name:String = "leon", address:String)

it seems the parser will complain about missing name even if I have a default value for it.

spray.json.DeserializationException: Object is missing required member 'name'
at spray.json.package$.deserializationError(package.scala:23)
at spray.json.ProductFormats$class.liftedTree1$1(ProductFormats.scala:489)
at spray.json.ProductFormats$class.spray$json$ProductFormats$$fromField(ProductFormats.scala:481)
at spray.json.ProductFormats$$anon$2.read(ProductFormats.scala:50)
at spray.json.ProductFormats$$anon$2.read(ProductFormats.scala:43)
at spray.json.JsValue.convertTo(JsValue.scala:32)
at com.ebay.raptor.proxy.LogHandler$$anonfun$receive$2.applyOrElse(LogService.scala:62)
at akka.actor.ActorCell.receiveMessage(ActorCell.scala:498)


How to resolve it?


Thanks
Ma Ling


在 2014年2月25日星期二UTC-8上午1时05分08秒,Johannes Rudolph写道:

Johannes Rudolph

unread,
Feb 25, 2014, 4:24:54 AM2/25/14
to Leon Ma, spray...@googlegroups.com
On Tue, Feb 25, 2014 at 10:22 AM, Leon Ma <tutu...@gmail.com> wrote:
> cool, I just tried and it works!
>
> But if the json is like this
>
> {
>
> "address" : "my address",
> "unknowfield1" : "blabla",
>
>
> }
>
> case class Info(name:String = "leon", address:String)

Yes, Scala's default parameters are not supported. If you have
optional fields you need to change the `name` parameter to type
`Option[String]`.

--

Leon Ma

unread,
Feb 25, 2014, 8:12:29 AM2/25/14
to spray...@googlegroups.com, Leon Ma, johannes...@googlemail.com
Got it! Thanks a lot!

在 2014年2月25日星期二UTC+8下午5时24分54秒,Johannes Rudolph写道:
Reply all
Reply to author
Forward
0 new messages