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.

0

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

2 Comments

attrs doesn't has getOrElse method. Can u explain a bit on how to implement using Option and use it in here.
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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.