krzasteka
krzasteka

Reputation: 427

How to escape all special characters in Scala

If I have a JSON string:

{"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"}

How can I assign it to a val s:String ?

Upvotes: 1

Views: 3321

Answers (1)

user1804599
user1804599

Reputation:

One way is to put it in a string literal (triple quotes allow using quotes inside the string literal without escaping):

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"}"""

Another way is to read it from a resource file, which may or may not be considered cleaner:

import scala.io.Source
val s = Source.fromURL(getClass.getResource("/data.json"), "UTF-8").mkString

Upvotes: 6

Related Questions