Sps-json JsString quotes string values

I am using json-spray. It appears that when I try to print the syntax value of JsString, it includes quotation marks at the end of the line.

val x1 = """ {"key1": "value1", "key2": 4} """ println(x1.asJson) println(x1.asJson.convertTo[Map[String, JsValue]]) 

What outputs:

 {"key1":"value1","key2":4} Map(key1 -> "value1", key2 -> 4) 

But this means that the string value key1 is actually quoted, since scala displays strings without their quotes. that is, val k = "value1" outputs: value1 not "value1" . Maybe I am doing something wrong, but the best I could come up with to facilitate this was as follows:

 val m = x1.asJson.convertTo[Map[String, JsValue]] val z = m.map({ case(x,y) => { val ny = y.toString( x => x match { case v: JsString => v.toString().tail.init case v => v.toString() } ) (x,ny) }}) println(z) 

Which displays the correctly displayed string:

 Map(key1 -> value1, key2 -> 4) 

But this solution will not work for recursively nested JSON. Is there a better workaround?

+6
source share
3 answers

Try the following:

 import spray.json._ import DefaultJsonProtocol._ val jsString = new JsString("hello") val string = jsString.convertTo[String] 
+10
source

There is a slight difference in the new version:

libraryDependencies ++ = "io.spray"% "spray-json_2.12"% "1.3.3"

 import spray.json.DefaultJsonProtocol._ import spray.json._ object SprayJson extends ExampleBase { private def jsonValue(): Map[String, String] = { val x1 = """ {"key1": "value1", "key2": 4} """ val json = x1.parseJson println(json.prettyPrint) json.convertTo[Map[String, JsValue]].map(v => (v._1, v._2 match { case s: JsString => s.value case o => o.toString() })) } override def runAll(): Unit = { println(jsonValue()) } } 

Output:

 { "key1": "value1", "key2": 4 } Map(key1 -> value1, key2 -> 4) 
+1
source

I ran into the same problem. Delving into the source code, they use compactPrint, which seems great. I don't know at what point this happens with quotes

0
source

Source: https://habr.com/ru/post/959487/


All Articles