Dynamic Type with Jackson & Akka-http

22 views
Skip to first unread message

Pablo Mincz

unread,
Aug 4, 2015, 12:10:24 AM8/4/15
to Rapture users
Hi,

I am doing an API and I want to receive a JSON by POST, and It has to be dynamic because it can change, and if is a case class It will have 4554 fields.

Someone know how to do this? Or may be someone have an example of this?

Thanks a lot for your help.

Regards,
Pablo.

Jon Pretty

unread,
Aug 4, 2015, 5:04:06 AM8/4/15
to Rapture users
Hi Pablo,

Instead of extracting a case class, Rapture lets you extract a JSON value as a `Map[String, <something>]`, though you need to pick an appropriate <something>. If all your values were `String`s, then you can extract `Map[String, String]`, however, if they all have different types, it would be better to extract `Map[String, Json]`, and to perform a subsequent extraction on each one. Here's an example:

Say this JSON was posted:

   {
     "message": "Hello World",
     "count": 7
   }

If this is stored in a JSON value, `j`, we could get the values out like this:

   val jMap = j.as[Map[String, Json]]
   jMap("message").as[String]
   jMap("count").as[Int]

This is basically equivalent to using the dynamic types, though, e.g.:

   j.message.as[String]
   j.count.as[Int]

which are also easier to read.

Is this enough for your purposes? There is another possibility which takes a bit longer to explain, but would offer the safety that it would only allow you to access fields with names in your list of 4554 fields, and you wouldn't need to specify the type each time (but you would need to provide the list of field names and corresponding types in advance). I can explain this solution too, if you like.

Cheers,
Jon

Pablo Mincz

unread,
Aug 4, 2015, 9:44:45 AM8/4/15
to Rapture users
Hi Jon,

Thanks a lot for your help!!!

I think the other possibility may help me more, because I need to provide a list of fields that will be indexed in lucene, and may be I can use the same list.

But I want to know if I can skip some fields in the provided list and not access them.

Thanks!

Regards,
Pablo.
Reply all
Reply to author
Forward
0 new messages