我在Swift 5上解码json时出错

时间:2019-11-14 07:37:43

标签: json swift xcode parsing

我尝试解析后端团队制作的json。但是json有点奇怪,我不能要求后端团队更改json。所以这是json:

{
"nama": [
    "Tigor Franky",
    "Achmad Fauzi",
    "Mario David Lela Muda",
    "Mily Anggreini Hutasuhut",
    "Arif Fahmi ST",
    "Satwika Narindra Dhipa",
    "Mujib Burahman",
    "Aresty Puji Harjanty",
    "Rio Jatmiko",
    "Halasson Sitanggang"
],
"u_id": [
    196,
    113,
    114,
    149,
    115,
    116,
    117,
    118,
    119,
    120
],
"totalakhir": [
    14.15,
    1.74,
    1.25,
    0.75,
    0,
    0,
    0,
    0,
    0,
    0
   ]
 }

所以,这对我来说是新的。我该如何解码?

到目前为止,我尝试了此操作,但是出现了一个错误消息

  

“ typeMismatch(Swift.Dictionary,Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:” nama“,intValue:nil),_JSONKey(stringValue:” Index 0“,intValue:0)],debugDescription:”应该解码字典,但找到了一个字符串/数据。“,underlyingError:nil))”

我尝试制作这样的结构:

struct HOF : Codable {
let nama : [Nama]
let u_id : [U_Id]
let totalakhir : [TotalAkhir]
}

struct Nama : Codable {
let namaa : String

enum CodingKeys : String, CodingKey {
    case namaa = "nama"
   }
}

struct U_Id : Codable {
let u_idd : Int

enum CodingKeys : String, CodingKey {
    case u_idd = "u_id"
   }
}

我知道我在构造结构上错了,但是我只是不知道如何构造结构。

2 个答案:

答案 0 :(得分:2)

struct HOF更改为此,并删除其他数据类型,

struct HOF : Codable {
    let nama : [String]
    let u_id : [Int]
    let totalakhir : [Decimal]
}

似乎列表与同一用户相关,所以我建议您要求后端更改如下的json结构,

{
"hof": [
    {
      "nama": "Tigor Franky",
      "u_id": 196,
      "totalakhir": 14.15
    },
    {
      "nama": "Mily Anggreini Hutasuhut",
      "u_id": 113,
      "totalakhir": 1.74
    }
 ]
}

因此,您的数据类型将更改为此,

struct HofUser : Codable {
    let nama : String
    let u_id : Int
    let totalakhir : Decimal
}

struct Response : Codable {
    let hof : [HofUser]
}

这将使您仅具有一个列表,其中每个元素具有与特定用户有关的所有信息。

答案 1 :(得分:0)

由于字符串 Int Double 是可编码类型。 因此,一组Codable类型将与Codable一起使用。

因此无需为 U_Id Nama

键入类型

您可以按以下代码所示制作模型。 Codable将为您完成其余的工作。 您可以在操场上运行此示例,并查看解码后的输出。

$post['ID'] = $id;
$post['post_date'] = $publish_date;
$post['post_date_gmt'] = $publish_date;
wp_update_post($post);