【问题标题】:json4s parse return nulljson4s解析返回null
【发布时间】:2018-07-05 16:32:45
【问题描述】:

我正在尝试使用 scala 中的 json4s 从嵌套 JSON 中获取价值。 parse 方法适用于手动提供的字符串,但对于从文件提供的字符串为 null。 这是代码

import org.json4s.jackson.JsonMethods.{parse, pretty}
import scala.io.Source

object ParseJson4s {
  def map_fields(lines: String) = {
    val testString = """{"Information":{"Context":"firstContext", "Assets":{"Asset":{"Name":"firstName"}}}}"""
    val parseJSON_test = parse(testString)
    val parseJSON = parse(lines)

    println("Name from method " + pretty(parseJSON_test \ "Information" \ "Assets" \ "Asset" \ "Name"))
    println("Name from file " + pretty(parseJSON \ "Information" \ "Assets" \ "Asset" \ "Name"))
  }
  def main(args: Array[String]): Unit = {
    val file = Source.fromFile("testFile.txt").getLines()
    file.foreach(map_fields)
  }
}

这是测试文件

"""{"Information":{"Context":"firstContext", "Assets":{"Asset":{"Name":"firstName"}}}}"""
"""{"Information":{"Context":"secondContext", "Assets":{"Asset":{"Name":"secondName"}}}}"""

输出:

Name from method "firstName"
Name from file 
Name from method "firstName"
Name from file 

谢谢

【问题讨论】:

    标签: scala json4s


    【解决方案1】:

    对于您的文本文件中的 JSON 记录,""" 是强制性的吗?我删除了它们,它对我有用。

    我在控制台中得到的结果:

    Name from file "firstName" 
    Name from file "secondName"
    

    源代码:

    import org.json4s.jackson.JsonMethods.{parse, pretty}
    import scala.io.Source
    
    object Json4sTest {
      def map_fields(lines: String) = {
        val parseJSON = parse(lines)
        println("Name from file " + pretty(parseJSON \ "Information" \ "Assets" \ "Asset" \ "Name"))
      }
      def main(args: Array[String]): Unit = {
        val file = Source.fromFile("testFile.txt").getLines()
        file.foreach(map_fields)
      }
    }
    

    testFile.txt:

    {"Information":{"Context":"firstContext", "Assets":{"Asset":{"Name":"firstName"}}}}
    {"Information":{"Context":"secondContext", "Assets":{"Asset":{"Name":"secondName"}}}}
    

    【讨论】:

      【解决方案2】:

      失败的原因是文件中的行不是有效的 JSON 字符串。 JSON 字符串不能以三引号或引号开头,除非它只是一个简单的字符串。

      Scala 中的三引号(""") 用于创建多行字符串和其中包含引号的字符串。只有在 scala 中定义字符串字面量(硬编码字符串)时才需要使用它们。

      所以,从文件中的行中删除三引号,它应该会给你正确的结果。

      【讨论】:

        【解决方案3】:

        尝试用jsoniter-scala从文件中解析,它会清楚地报告问题的位置和原因。

        https://github.com/plokhotnyuk/jsoniter-scala

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-07-24
          • 2013-03-29
          • 1970-01-01
          • 2016-02-12
          • 2021-09-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多