简体   繁体   中英

Parse JSON in Scala using JSON4S

I have some response data in JSON format:

{ "items" : 
    [
    {"commentId" : "28444760","userId" : "142607","userIP" : "","userName" : "Rock'n'Roll ","userAvatar" : "/i/default_userpic.png ","userIsBlock" : false,"userBanDate" : "",
    "userCountry" : "http://ikor.ill.in.ua/f/UA.gif","date" : "16.02.2017, 17:07","text" : "txt","rate" : 2,"isLikeExist" : false,"childComments" : []}
    ]
}

and I want to parse it to lists. For example, to extract commentId I use:

val js = parse(json)\\"items"
val commentId:List[String] = js\\"commentId"\ classOf[JString]

and I get list with id

when I tried parsing date I got:

List(16.02.2017, 17:24, 16.02.2017, 17:23)

How I can return the date list in the format List("date time")?

This is how you can parse date/times with a format specification:

def parseDT(s: String) = {
 val fmt = "dd.MM.yyyy, HH:mm"
 val df = java.time.format.DateTimeFormatter.ofPattern(fmt)
 java.time.LocalDateTime.parse(s, df)
}

So after you get the dates from JSON (as strings) parse them: val dates = datesFromJSON.map(parse(_))

If all you want is to remove the comma from the date strings, you can do val dates = datesFromJSON.map(s => s.replaceAll(",",""))

The solution in my case is:

val dateFormat  = new SimpleDateFormat("dd.MM.yyyy, HH:MM")
val date:List[java.util.Date] = (js\\"date").children.map(x=>dateFormat.parse(x.values.toString))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM