当字段是 scala 关键字时,如何自动将 JSON 映射到 case 类? [英] How can I automatically map JSON to a case class when a field is a scala keyword?

查看:71
本文介绍了当字段是 scala 关键字时,如何自动将 JSON 映射到 case 类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Play 框架 (2.6) 中;我目前正在自动映射 JSON到来自MongoDB的案例类(使用ReactiveMongo 0.12 带有 JSON 集合).我已经下载了一个数据集(here)并将其导入MongoDB 作为一个集合,以便进行一些与地理空间查询相关的测试.然而,其中一个字段称为type"(快速浏览您会看到这个here) 所以我遇到了问题,因为这是 Scala 中的关键字.否则我会这样写:

Within the Play Framework (2.6); I am currently automatically mapping JSON to case classes from MongoDB (using ReactiveMongo 0.12 with JSON Collections). I have downloaded a dataset (here) and imported it into MongoDB as a collection in order to do some testing relating to geospatial queries. However one of the fields is called "type" (at a quick glance you will see this here) so I am having issues as this is a keyword in Scala. This would otherwise be what I would write:

   case class Geometry(coordinates: List, type: String)
   case class Neighborhood(_id: Option[BSONObjectID], geometry: Geometry, name: String)

非常感谢这里的任何建议!

补充一下(感谢@MarioGalic);将 scala 关键字 声明为类参数名称似乎是用反引号完成的,但我仍然遇到在 Play 模板 中输出这些内容的问题.所以如果我循环遍历每个文档,我可能会写这个(这是一个错误).

Many thanks for any suggestions here!

Just to add (thanks to @MarioGalic); declaring scala keywords as class parameter names seems to be done with backticks but I am still having an issue outputting these in the Play templates. So if I was looping through each document I might write this (which is getting an error).

   @for(ngh <- neighborhoods){
     <tr>
        ...
        <td>@ngh.name</td>
        <td>@ngh.geometry.`type`</td>
        ...
     </tr>
   }

没有反引号在这里不起作用,并且在模板中不能识别反引号.我在这个关于该主题的参考问题/答案中找不到任何其他格式 所以我还是有问题.谢谢

Without backticks doesn't work here and with backticks aren't recognised within the template. I cannot find any other formats in this referenced question/answer on the subject so I am still having an issue. Thanks

抱歉,这很明显要做什么.在案例类模型中,只需定义一个具有不同名称的方法(与本示例中的类型"不同,但基本上是任何导致问题的关键字:

Sorry this is obvious as to what to do. Within the case class model just define a method that has a different name (from "type" in this example but essentially any keyword which is causing an issue:

   case class Geometry(coordinates: List, `type`: String) {
      def getType = `type`
   }

然后在模板中调用它:

   @for(ngh <- neighborhoods){
     <tr>
        ...
        <td>@ngh.name</td>
        <td>@ngh.geometry.getType</td>
        ...
     </tr>
   }

谢谢大家!

推荐答案

您可以使用 type 包裹起来rel="nofollow noreferrer">反引号 像这样:

You could wrap the field type with backticks like so:

case class Geometry(coordinates: List, `type`: String)

以下答案更详细地解释了反引号语法:需要澄清 Scala 文字标识符(反引号)

The following answer explains backticks syntax in more detail: Need clarification on Scala literal identifiers (backticks)

这篇关于当字段是 scala 关键字时,如何自动将 JSON 映射到 case 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆