简体   繁体   English

如何处理JSON数据中的错误不正确的节点

[英]How to handle error in JSON data has incorrect is node

I'm expecting following json format: 我期望以下json格式:

'{
  "teamId" : 9,
  "teamMembers" : [ {
    "userId" : 1000
  }, {
    "userId" : 2000
  }]
}'

If I test my code with following format:- 如果我使用以下格式测试代码:

'{
  "teaXmId" : 9,
  "teamMembers" : [ {
    "usXerId" : 1000
  }, {
    "userXId" : 2000
  }]
}' 

I'm parsing json value as follows:- 我正在解析json值,如下所示:

val userId = (request.body \\ "userId" )
val teamId = (request.body \ "teamId")
val list = userId.toList
list.foreach( x => Logger.info("x val: "+x)

It doesn't throw any error to handle. 它不会抛出任何错误要处理。 Code execution goes one. 代码执行合而为一。 Later if I try to use teamId or userId, of course it doesn't work then. 稍后,如果我尝试使用teamId或userId,则当然不起作用。

So how to check whether parsing was done correctly or stop execution right away and notify user to provide correct json format 那么如何检查解析是否正确完成或立即停止执行并通知用户提供正确的json格式

If a value is not found when using \\ , then the result will be of type JsUndefined(msg) . 如果使用\\时未找到值,则结果将为JsUndefined(msg)类型。 You can throw an error immediately by making sure you have the type you expect: 您可以通过确保具有所需的类型来立即引发错误:

 val teamId = (request.body \ "teamId").as[Int]

or: 要么:

val JsNumber(teamId) = request.body \ "teamId" //teamId will be BigDecimal

When using \\\\ , if nothing is found, then an empty List is returned, which makes sense. 使用\\\\ ,如果未找到任何内容,则返回一个空的List ,这很有意义。 If you want to throw an error when a certain key is not found on any object of an array, you might get the object that contains the list and proceed from there: 如果要在数组的任何对象上都找不到某个键时引发错误,则可以获取包含列表的对象并从那里继续:

val teamMembers =  (request.body \"teamMembers").as[Seq[JsValue]]

or: 要么:

val JsObject(teamMembers) = request.body \ "teamMembers"    

And then: 接着:

val userIds = teamMembers.map(v => (v \ "userId").as[Int])

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

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