【发布时间】:2020-11-29 17:24:49
【问题描述】:
我正在学习一个使用 Whitehouse 请愿 JSON 提要的在线教程。我正在使用 Swift 5 并且已经实现了我的结构以符合 Codable。 Whitehouse JSON 导致 Codable 错误。下面是 JSON 的 sn-p。引起麻烦的部分是“响应”。在第一个示例中,我希望它是一个空数组,但是当它具有第二个示例中的值时,JSON 从 [] 切换到 {},如下所示。
[ ] 示例:
"results":[
{
"id":"2722358",
"type":"petition",
"title":"Remove Chuck Schumer and Nancy Pelosi from office",
"body":"Schumer and Pelosi's hatred and refusing to work with...",
"petition_type":[
{
"id":291,
"name":"Call on Congress to act on an issue"
}
],
"signatureThreshold":100000,
"status":"closed",
"response":[
],
"created":1547050064,
"isSignable":false,
"isPublic":true,
"reachedPublic":0
},
{ } 示例
"results":[
{
"id":"2722358",
"type":"petition",
"title":"Remove Chuck Schumer and Nancy Pelosi from office",
"body":"Schumer and Pelosi's hatred and refusing to work with...",
"petition_type":[
{
"id":291,
"name":"Call on Congress to act on an issue"
}
],
"signatureThreshold":100000,
"status":"closed",
"response":{
"id":2630367,
"url":"https://petitions.whitehouse.gov/response/response-your-petition-3",
},
"created":1547050064,
"isSignable":false,
"isPublic":true,
"reachedPublic":0
},
从我对该问题的研究中可以看出,JSON 的编写应该一致。换句话说,由于“响应”从来都不是一个数组,而只是一个单一的值,所以当它为空时应该写为 { } 而不是 [ ] 。我对此的理解正确吗?
【问题讨论】:
-
嗯。它称它为有效。即使其中一个显示为 [ ] 和一个显示为 { },其中包含内容。 Codable 抛出一个错误,基本上说是预期的数组。
-
谢谢@dratenik。为了便于阅读,我把正文删掉了,忘记加引号了。
-
而且,我一如既往地感谢投反对票...不知道为什么我回到这个网站。
-
不确定这是否有帮助? stackoverflow.com/questions/52681385/…
-
这是另一篇文章:medium.com/@sajjadsarkoobi/…