如果我有一个JSON字符串:
{"location":"Irvine","role":"Owsla","resident":{"years":15,"deposit":true},"car":"BMW","multiple-residents":{"number":4,"name":"Fiver","role":{"employer":"ResortShare","computer":{"make":"mac","model":"air"},"comapny-car":false},"age":4,"position":"Fiver"},"age":"6","name1":"Bob","nick-name":"Bigwig"}
如何将其分配给val s:String
?
答案 0 :(得分:5)
一种方法是将它放在字符串文字中(三引号允许在字符串文字中使用引号而不转义):
val s = """{"location":"Irvine","role":"Owsla","resident":{"years":15,"deposit":true},"car":"BMW","multiple-residents":{"number":4,"name":"Fiver","role":{"employer":"ResortShare","computer":{"make":"mac","model":"air"},"comapny-car":false},"age":4,"position":"Fiver"},"age":"6","name1":"Bob","nick-name":"Bigwig"}"""
另一种方式是read it from a resource file,可能会或可能不会被认为更清洁:
import scala.io.Source
val s = Source.fromURL(getClass.getResource("/data.json"), "UTF-8").mkString