patternModerate
Parsing JSON to a Map and Set structure
Viewed 0 times
mapandparsingstructurejsonset
Problem
How do I make these line of codes more scala-ish (shorter?). I still get the Java feeling in it (which I want to stay away from).
import scala.collection.mutable
val outstandingUserIds: mutable.LinkedHashSet[String] = mutable.LinkedHashSet[String]()
val tweetJson = JacksMapper.readValue[Map[String, AnyRef]](body)
val userObj = tweetJson.get("user")
tweetJson.get("user").foreach(userObj => {
userObj.asInstanceOf[Map[String, AnyRef]].get("id_str").foreach(idStrObj => {
if (outstandingUserIds.exists(outstandingIdStr => outstandingIdStr.equals(idStrObj))) {
outstandingUserIds.remove(idStrObj.asInstanceOf[String])
}
})
})Solution
If you really want to inflict this JSON library on yourself, your code could be simplified to:
But I would recommend you use a better JSON library. For example, using the library that comes with the Play! framework:
import scala.collection.mutable
val outstandingUserIds = mutable.LinkedHashSet[String]()
val tweetJson = JacksMapper.readValue[Map[String, AnyRef]](body)
for {
userObj <- tweetJson.get("user")
idStrObj <- userObj.asInstanceOf[Map[String, AnyRef]].get("id_str")
} outstandingUserIds -= idStrObj.asInstanceOf[String]But I would recommend you use a better JSON library. For example, using the library that comes with the Play! framework:
(body \ "user" \ "id_str").asOpt[String].foreach {id =>
outstandingUserIds -= id
}Code Snippets
import scala.collection.mutable
val outstandingUserIds = mutable.LinkedHashSet[String]()
val tweetJson = JacksMapper.readValue[Map[String, AnyRef]](body)
for {
userObj <- tweetJson.get("user")
idStrObj <- userObj.asInstanceOf[Map[String, AnyRef]].get("id_str")
} outstandingUserIds -= idStrObj.asInstanceOf[String](body \ "user" \ "id_str").asOpt[String].foreach {id =>
outstandingUserIds -= id
}Context
StackExchange Code Review Q#54014, answer score: 10
Revisions (0)
No revisions yet.