Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala json4s解析返回null_Scala_Json4s - Fatal编程技术网

Scala json4s解析返回null

Scala json4s解析返回null,scala,json4s,Scala,Json4s,我试图在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

我试图在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 

谢谢

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

您的文本文件中是否有mandadory for JSON记录?我移除了它们,它对我有效

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

Name from file "firstName" 
Name from file "secondName"
源代码:

testFile.txt:


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

scala中的三重引号用于创建多行字符串以及其中包含引号的字符串。只有在scala中定义字符串literalshard代码字符串时才需要使用它们

因此,从文件中的行中删除三重引号,它将为您提供正确的结果

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)
  }
}
{"Information":{"Context":"firstContext", "Assets":{"Asset":{"Name":"firstName"}}}}
{"Information":{"Context":"secondContext", "Assets":{"Asset":{"Name":"secondName"}}}}