我在scala.js世界中很新,所以我决定在一些小的例子上尝试它,其中一个非常简单的get请求,解析返回到scala实体中的json。
请查找以下代码:
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(stringify)返回以下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))谢谢您的澄清。
发布于 2016-06-09 01:42:55
事实上,正确的答案就在这里:upickle read from scalaJS - upickle.Invalid$Data: String (data: 1)
字符串只是部分正确的答案。您还可以使用Double (至少可以从scala端的实际长时间免费转换)。
因此,我得到了以下实体,它工作得很好:
case class Post(title: String,
content: String,
tags: List[String] = List.empty,
created: Double = System.currentTimeMillis())发布于 2016-06-08 19:17:02
uPickle在JSON中将Long序列化为字符串,因为JavaScript数字不能表示所有Long的字符串。
因此,对象的created字段应该是字符串"1474606780004"。
https://stackoverflow.com/questions/37689453
复制相似问题