【发布时间】:2016-10-07 22:50:18
【问题描述】:
我是 scala.js 领域的新手,所以我决定尝试一些小示例,其中一个是非常简单的获取请求,将返回的 json 解析回 scala 实体。
请在下面找到执行此操作的代码:
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))
提前感谢您的澄清。
【问题讨论】:
-
我相信 upickle 将
Longs 序列化为 JSON 字符串。尝试在手动实例化的帖子列表上调用write,并将输出与您的stringify字符串进行比较。 -
作为替代方案:你能不能调用
readJs而不是read,传递data而不是stringify? -
将回调签名更改为数据:Js.Value 并调用 readJs 方法会导致此异常:scala.scalajs.runtime.UndefinedBehaviorError:检测到未定义的行为:[object Object],[object Object],[ object Object],[object Object],[object Object] 不是 upickle.Js$Value 的实例
-
编辑的问题,写的例子也不起作用
-
你能把
write的结果贴出来吗?