将JValue转换为JSON字符串

时间:2017-03-17 11:11:48

标签: scala json4s

我想将jvalue转换为json字符串。这是我的代码的样子:

import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.native.JsonMethods._
import org.json4s.DefaultFormats._

 object Json4sTest {

  def main(arg: Array[String]) {
    var json = parse("""{"name":"luca", "id": "1q2w3e4r5t", "age": 26, "inner": { "age": 27 }, "url":"http://    www.nosqlnocry.wordpress.com"}""")
 //   println(json)

    val a: List[Map[String, JValue]] = List(Map("inner/age" -> 35, "age" -> 27), Map("name" -> "foo"))
    val r = jsonFieldUpdater(json, a)
    println(r)

        }


      def jsonFieldUpdater(json: JValue, list: List[Map[String, JValue]]): JValue =
    //
      }
    }

得到结果:

JObject(List((name,JString(foo)), (id,JString(1q2w3e4r5t)), (age,JInt(27)), (inner,JObject(List((age,JInt(35))))), (url,JString(http://    www.nosqlnocry.wordpress.com))))

我正在寻找一个Json String输出:

{"name":"luca", "id": "1q2w3e4r5t", "age": 27, "inner": { "age": 35 }, "url":"http://    www.nosqlnocry.wordpress.com"}

1 个答案:

答案 0 :(得分:3)

如果要打印JValue的字符串表示,可以通过以下方式执行: println(compact(render(r)))

这样,方法String收到的compact(render(r))如下所示:

{"lotto":{"lotto-id":5,"winning-numbers":[2,45,34,23,7,5,3],"winners":[{"winner-id":23,"numbers":[2,45,34,23,3,5]},{"winner-id":54,"numbers":[52,3,12,11,18,22]}]}}

或者你可以使用println(pretty(render(r)))来获得漂亮的String

{
  "lotto":{
    "lotto-id":5,
    "winning-numbers":[2,45,34,23,7,5,3],
    "winners":[{
      "winner-id":23,
      "numbers":[2,45,34,23,3,5]
    },{
      "winner-id":54,
      "numbers":[52,3,12,11,18,22]
    }]
  }
}

documentation使用的示例。