简体   繁体   English

使用JSON4S在Scala中解析JSON

[英]Parse JSON in Scala using JSON4S

I have some response data in JSON format: 我有一些JSON格式的响应数据:

{ "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: 例如,要提取commentId ,请使用:

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

and I get list with id 我得到带有ID的列表

when I tried parsing date I got: 当我尝试解析date我得到:

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

How I can return the date list in the format List("date time")? 如何返回格式为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(_)) 因此,从JSON(以字符串形式)获取日期后,将其解析为: 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(",","")) 如果您只想从日期字符串中删除逗号,则可以执行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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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