![](/img/trans.png)
[英]Array is not an array anymore after getting stringified and parsed (JSON)
[英]Scala play api for JSON - getting Array of some case class from stringified JSON?
從我們的代碼中,我們調用一些服務,並返回字符串化的JSON結果。 字符串化的JSON是一個“ SomeItem”數組,其中只有四個字段-3個Longs和1個String
例如:
[
{"id":33,"count":40000,"someOtherCount":0,"someString":"stuffHere"},
{"id":35,"count":23000,"someOtherCount":0,"someString":"blah"},
...
]
我一直在使用play API通過隱式Writes / Reads讀取值。 但是我很難讓它為數組工作。
例如,我一直在嘗試從響應中解析出值,然后將其轉換為SomeItem case類數組,但是失敗了:
val sanityCheckValue: JsValue: Json.parse(response.body)
val Array[SomeItem] = Json.fromJson(sanityCheckValue)
我有
implicit val someItemReads = Json.reads[SomeItem]
但看起來好像沒有用。 我也試圖建立一個Json.reads [Array [SomeItem]],但是沒有運氣。
這應該工作嗎? 有關如何使其正常工作的任何提示?
import play.api.libs.json._
case class SomeItem(id: Long, count: Long, someOtherCount: Long, someString: String)
object SomeItem {
implicit val format = Json.format[SomeItem]
}
object PlayJson {
def main(args: Array[String]): Unit = {
val strJson =
"""
|[
| {"id":33,"count":40000,"someOtherCount":0,"someString":"stuffHere"},
| {"id":35,"count":23000,"someOtherCount":0,"someString":"blah"}
|]
""".stripMargin
val listOfSomeItems: Array[SomeItem] = Json.parse(strJson).as[Array[SomeItem]]
listOfSomeItems.foreach(println)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.