2015-02-09 58 views
0

在斯卡拉序列化JSON,我怎麼能去序列化JSON字符串,修改值和序列化回字符串?解析/使用Scala

必須有一個辦法做到這一點,而無需使用第三方庫,但我無法得到它的工作。以下是我試過到目前爲止:

import scala.util.parsing.json 

var lines = "{\"id\" : \"abc\", \"stuff\" : [1, 2, 3], \"more\" : {\"bro\" : \"science\"}}" 

// Test 1 
val myJSON = json.JSON.parseRaw(lines) 
// myJSON: Option[scala.util.parsing.json.JSONType] = Some({"id" : "abc", "stuff" : [1.0, 2.0, 3.0], "more" : {"bro" : "science"}}) 
// I cannot modify fields on the JSONType instance but toString() works well. 
// res1: String = Some({"id" : "abc", "stuff" : [1.0, 2.0, 3.0], "more" : {"bro" : "science"}}) 

// Test 2 
// This way I can parse JSON into a map and manipulate its values. 
// val myMap = json.JSON.parseFull(lines).get.asInstanceOf[Map[String, Any]] + ("id" -> "blah") 
// myMap: scala.collection.immutable.Map[String,Any] = Map(id -> blah, stuff -> List(1.0, 2.0, 3.0), more -> Map(bro -> science)) 

// However, when converted to an instance of JSONObject and calling 
// toString() only the top-level items are JSON-serialized 
new json.JSONObject(myMap).toString() 
// res2: String = {"id" : "blah", "stuff" : List(1.0, 2.0, 3.0), "more" : Map(bro -> science)} 

如果它不可能與標準斯卡拉,我會很感激,並舉例如何與第三方庫做到這一點。

感謝,

/大衛

+1

http://stackoverflow.com/questions/4170949/how-to-parse-json-in-scala-using-standard-scala-classes的可能的複製,雖然時下JSON解析器與解析器組合似乎被棄用(太緩慢,無人維持)。尋找替代品:http://softwarerecs.stackexchange.com/。 – 2015-02-09 12:24:39

+5

有許多JSON庫(例如淘金者,玩,JSON,電梯,JSON,...) – cchantep 2015-02-09 12:41:47

+0

我一直使用https://github.com/json4s/json4s取得了一些成功。它有一個很好的API。 – 2015-02-09 14:06:12

回答

1

小傻/瑣碎的什麼我提到的例子。可以寫得更好,但想把它分成塊。有很多,你可以與他們無關:

這是在打版方面舊的鏈接,但據我所知,最新在2.3.x版本提供的功能:

https://www.playframework.com/documentation/2.1.1/ScalaJsonTransformers

import play.api.libs.json._ 

var lines = "{\"id\" : \"abc\", \"stuff\" : [1, 2, 3], \"more\" : {\"bro\" :  \"science\"}}" 

val jsonAsJsValue = Json.parse(lines) 
//jsonAsJsValue: play.api.libs.json.JsValue = {"id":"abc","stuff": [1,2,3],"more":{"bro":"science"}} 
val updateIdTransformer = (__ \"id").json.update(
__.read[JsString].map{a => JsString("def")} 
) 

val updatedJson = jsonAsJsValue.transform(updateIdTransformer) 

//updatedJson: play.api.libs.json.JsResult[play.api.libs.json.JsObject] = JsSuccess({"id":"def","stuff":[1,2,3],"more":{"bro":"science"}},/id)