【问题标题】:Parsing bad Json in Scala在 Scala 中解析错误的 Json
【发布时间】:2018-12-28 18:40:40
【问题描述】:

我正在尝试使用 Play Json 和隐式解析 Scala 中的一些有问题的 Json,但不确定如何继续...

Json 看起来像这样:

"rules": {
    "Some_random_text": {
      "item_1": "Some_random_text",
      "item_2": "text",
      "item_n": "MoreText",
      "disabled": false,
      "Other_Item": "thing",
      "score": 1
    },
    "Some_other_text": {
      "item_1": "Some_random_text",
      "item_2": "text",
      "item_n": "MoreText",
      "disabled": false,
      "Other_Item": "thing",
      "score": 1
    },
    "Some_more_text": {
      "item_1": "Some_random_text",
      "item_2": "text",
      "item_n": "MoreText",
      "disabled": false,
      "Other_Item": "thing",
      "score": 1
    }
}

我使用的是隐式阅读器,但因为 rules 中的每个顶级项目实际上都是不同的东西,我不知道如何解决这个问题......

我正在尝试构建一个案例类,我实际上并不需要每个项目的随机文本标题,但我确实需要每个项目。

为了让我的生活更加艰难,因为这些项目中有很多我真的不需要的其他格式的东西。它们是刚开始的未命名项目: { 随机合法的Json ... }, { 更多 Json... }

我需要在一系列案例类中解析我正在解析的 Json。

感谢您的意见。

【问题讨论】:

    标签: json scala


    【解决方案1】:

    我使用的是隐式阅读器,但因为规则中的每个顶级项目实际上都是不同的东西,我不知道如何解决这个问题......

    播放 JSON 阅读器依赖于预先知道字段的名称。这适用于手动构建的阅读器以及宏生成的阅读器。在这种情况下,您不能使用隐式阅读器。您需要先进行一些遍历并提取具有已知名称和字段类型的规则结构的 Json 片段。例如。像这样:

      case class Item(item_1: String, item_2: String, item_n: String, disabled: Boolean, Other_Item: String, score: Int)
    
      implicit val itemReader: Reads[Item] = Json.reads[Item]
    
      def main(args: Array[String]): Unit = {
        // parse JSON text and assume, that there is a JSON object under the "rules" field
        val rules: JsObject = Json.parse(jsonText).asInstanceOf[JsObject]("rules").asInstanceOf[JsObject]
        // traverse all fields, filter according to field name, collect values
        val itemResults = rules.fields.collect {
          case (heading, jsValue) if heading.startsWith("Some_") => Json.fromJson[Item](jsValue) // use implicit reader here
        }
        // silently ignore read errors and just collect sucessfully read items
        val items = itemResults.flatMap(_.asOpt)
        items.foreach(println)
      }
    

    打印:

    Item(Some_random_text,text,MoreText,false,thing,1)
    Item(Some_random_text,text,MoreText,false,thing,1)
    Item(Some_random_text,text,MoreText,false,thing,1)
    

    【讨论】:

    • 谢谢。看起来不错,但我暗示每个项目都以“Some”开头,因为它是完全随机的。我还需要根据本节之后的规则处理其他对象并且没有起始字段,它们只是以“{”(左大括号)开头。
    • 将 startsWith 更改为正则表达式匹配,这很有效。谢谢!
    • rules 下的其他对象在没有起始字段的情况下无法启动,是吗?它不再是有效的 JSON。您是在谈论 JSON 数组吗?请向我们展示一个给您带来麻烦的示例。
    • 不,他们不是,现在这对我有用......一旦我正确地看待这一切,这一切都是有道理的,现在已经对其进行了测试,它为我带来了良好的结果。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2018-10-27
    • 2019-05-20
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多