0

I am fairly new to scala and functional programming. I have this piece of code written by someone which constructs json using json4s library,

val json = "body" -> ...toList.map {
  case (title, attrs) =>
    ("name", tag) ~ ("attributes", attrs)
}
val finalJson = compact(render(json))

All i understood on seeing this is, it constructs a json with given fields.

If attrs has value then its constructs json body with name and attributes. But if attrs is null, then I get below exception.

java.lang.NullPointerException:
  at org.json4s.JsonDSL$class.map2jvalue(JsonDSL.scala:71)
  at org.json4s.JsonDSL$.map2jvalue(JsonDSL.scala:61)

Searched several so posts and couldnt get hold of how to get it working. Closest one i got is this post

I think I have to utilize None and Option. Any ideas on how to fix this and probably an explanation would be really helpful if i misunderstood something.

Community
  • 1
  • 1
raksja
  • 3,969
  • 5
  • 38
  • 44

1 Answers1

1

You can try using getOrElse as below:

val json = "body" -> ...toList.map {
case (title, attrs) =>
("name", tag) ~ ("attributes", Option(attrs).getOrElse("")))
}
val finalJson = compact(render(json))
Samar
  • 2,091
  • 1
  • 15
  • 18
  • attrs doesn't has getOrElse method. Can u explain a bit on how to implement using Option and use it in here. – raksja Aug 16 '16 at 06:33
  • Please see edit. I am assuming that the toList method in: "body" -> ...toList.map produces tuples in which the second element of tuple (attrs) could be "null" – Samar Aug 16 '16 at 06:47