我在scala.js世界很新,所以我決定嘗試一些小例子,其中一個很簡單,獲取請求並解析返回到scala實體的json。upickle:在反序列化過程中無效的字符串值
請找出代碼,做它下面:
def loadAndDisplayPosts(postsElement: Element) = {
jQuery.get(
url = "/posts",
success = {
(data: js.Any) =>
val stringify = JSON.stringify(data)
console.log(stringify)
val posts = read[List[Post]](stringify)
console.log(posts.size)
posts.map(render).foreach(postsElement.appendChild)
}
)
}
的console.log(字符串化)返回以下JSON:
[
{
"title": "Some fancy title",
"content": "some very long string with \"escaped\" characters",
"tags": [
"algorithms"
],
"created": 1474606780004
}
]
而當一切都歸結爲
read[List[Post]](stringify)
我收到以下例外情況:
upickle.Invalid$Data: String (data: 1474606780004)
所以問題是:是否有什麼是做錯了?有這種行爲的一些有效理由嗎?
版庫的使用:
"com.lihaoyi" %%% "upickle" % "0.4.1"
編輯:
添加實體本身:
case class Post(title: String,
content: String,
tags: List[String] = List.empty,
created: Long = System.currentTimeMillis())
編輯2:
下面的代碼產生相同的誤差:
val post = Post("Some title", "some \"content\"", List("algorithms"), 1474606780004L)
val json = write[List[Post]](List(post))
在此先感謝您的澄清。
我相信upickle連載'Long's爲JSON字符串。嘗試在手動實例化的帖子列表上調用'write'並將輸出與'stringify'字符串進行比較。 –
作爲替代方案:你可以調用'readJs'而不是'read',傳遞'data'而不是'stringify'? –
將回調簽名更改爲data:Js.Value並調用readJs方法導致此異常:scala.scalajs.runtime.UndefinedBehaviorError:檢測到未定義的行爲:[object Object],[object Object],[object Object],[object Object ],[object Object]不是upickle的實例。Js $值 – tkachuko