如何在Swift 4中解析复杂的JSON

时间:2022-03-01 16:28:25

I need help with parsing JSON from server. Here's the JSON:

我需要从服务器解析JSON的帮助。JSON:

{
"response": {
    "items": [
        {
            "type": "post",
            "source_id": -17507435,
            "date": 1514538602,
            "post_id": 4105,
            "post_type": "post",
            "text": "Some text here",
            "marked_as_ads": 0,
            "attachments": [
                {
                    "type": "photo",
                    "photo": {
                        "id": 456239655,
                        "album_id": -7,
                        "owner_id": -17507435,
                        "user_id": 100,
                        "photo_75": "https://sun1-3.userapi.com/c840632/v840632924/3b7e7/4YUS7DlaLK8.jpg",
                        "photo_130": "https://sun1-3.userapi.com/c840632/v840632924/3b7e8/Ffpb4ZUlulI.jpg",
                        "photo_604": "https://sun1-3.userapi.com/c840632/v840632924/3b7e9/-pkl6Qdb9hk.jpg",
                        "width": 439,
                        "height": 312,
                        "text": "",
                        "date": 1514538602,
                        "post_id": 4105,
                        "access_key": "6a61a49570efd9c39c"
                    }
                }
            ],
            "post_source": {
                "type": "api"
            },
            "comments": {
                "count": 0,
                "groups_can_post": true,
                "can_post": 1
            },
            "likes": {
                "count": 0,
                "user_likes": 0,
                "can_like": 1,
                "can_publish": 1
            },
            "reposts": {
                "count": 0,
                "user_reposted": 0
            },
            "views": {
                "count": 2
            }
        }
    ],
    "profiles": [],
    "groups": [
        {
            "id": 17507435,
            "name": "Literature Museum",
            "screen_name": "samlitmus",
            "is_closed": 0,
            "type": "group",
            "is_admin": 0,
            "is_member": 1,
            "photo_50": "https://pp.userapi.com/c615722/v615722068/e58c/d5Y8E_5689s.jpg",
            "photo_100": "https://pp.userapi.com/c615722/v615722068/e58b/Hm05ga3x2J8.jpg",
            "photo_200": "https://pp.userapi.com/c615722/v615722068/e589/yoG_DDalFII.jpg"
        },
        {
            "id": 27711883,
            "name": "E:\\music\\melodic hardcore",
            "screen_name": "e_melodic_hc",
            "is_closed": 0,
            "type": "page",
            "is_admin": 0,
            "is_member": 1,
            "photo_50": "https://pp.userapi.com/c628220/v628220426/47092/xepNnC7pSBw.jpg",
            "photo_100": "https://pp.userapi.com/c628220/v628220426/47091/uAokr-c3NQ8.jpg",
            "photo_200": "https://pp.userapi.com/c628220/v628220426/4708f/eNY4vzooz4E.jpg"
        },
        {
            "id": 81574241,
            "name": "DOS4GW.EXE",
            "screen_name": "dos4gw",
            "is_closed": 0,
            "type": "page",
            "is_admin": 0,
            "is_member": 1,
            "photo_50": "https://pp.userapi.com/c622118/v622118651/e045/vlhV6QxtoLI.jpg",
            "photo_100": "https://pp.userapi.com/c622118/v622118651/e044/P9mVUhXBV58.jpg",
            "photo_200": "https://pp.userapi.com/c622118/v622118651/e043/Soq8oxCMB0I.jpg"
        },
        {
            "id": 76709587,
            "name": "Prosvet",
            "screen_name": "prosvet_pub",
            "is_closed": 0,
            "type": "page",
            "is_admin": 0,
            "is_member": 0,
            "photo_50": "https://pp.userapi.com/c630431/v630431500/b24a/GHox8AmDTXU.jpg",
            "photo_100": "https://pp.userapi.com/c630431/v630431500/b249/H3mcC-K7htM.jpg",
            "photo_200": "https://pp.userapi.com/c630431/v630431500/b248/9fyvB8gkcwc.jpg"
        }
    ],
    "next_from": "1/4105_1514494800_5"
}

}

}

What I need to get from this JSON are lines: "text", "comments", "likes", "reposts", "attachments".

我需要从这个JSON中得到的是行:“text”、“comments”、“like”、“repost”、“attachments”。

Inside "attachments" field I want to get "photo_604" line.

在“附件”字段中,我想获取“photo_604”行。

Here's my code:

这是我的代码:

class NewsItems: Decodable {
    var text: String?
    var comments: Comments
    var likes: Likes
    var reposts: Reposts
    var attachments: [Attachments]
}

class Comments: Decodable {
    var count: Int?
}

class Likes: Decodable {
    var count: Int?
}

class Reposts: Decodable {
    var count: Int?
}

class Attachments: Decodable {
    var attachments: AttachmentPhoto
}

class AttachmentPhoto: Decodable {
    var photo: WhatIsInsideAttachmentsPhoto
}

class WhatIsInsideAttachmentsPhoto: Decodable {
    var photo: String?

    enum CodingKeys: String, CodingKey {
        case photo = "photo_604"
    }
}


class WhatIsIsideResponseNewsFeed: Decodable {
    var items: [NewsItems]
}

public class ResponseNewsFeed: Decodable {
    var response: WhatIsIsideResponseNewsFeed
}

But after making the request:

但在提出要求后:

Alamofire.request(baseURL+methodName, parameters: parameters).responseData(completionHandler: { response in
        if let result = response.result.value {
            let decoder = JSONDecoder()
            let myResponse = try! decoder.decode(ResponseNewsFeed.self, from: result)
            completion(myResponse.response.items)

I get an error:

我得到一个错误:

Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.keyNotFound(_UL_PetrovLeonid.NewsItems.(CodingKeys in _FA9A2FC8130449AA328C19ACD9506C2D).attachments, Swift.DecodingError.Context(codingPath: [_UL_Leonid.ResponseNewsFeed.(CodingKeys in _FA9A2FC8130449AA328C19ACD9506C2D).response, _UL_PetrovLeonid.WhatIsIsideResponseNewsFeed.(CodingKeys in _FA9A2FC8130449AA328C19ACD9506C2D).items, Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 0", intValue: Optional(0))], debugDescription: "No value associated with key attachments (\"attachments\").", underlyingError: nil))

致命错误:“试试!这个短语意外地提出了一个错误:Swift.DecodingError.keyNotFound(_UL_PetrovLeonid.NewsItems)。(CodingKeys _FA9A2FC8130449AA328C19ACD9506C2D)。附件,Swift.DecodingError。上下文(codingPath:[_UL_Leonid.ResponseNewsFeed。(CodingKeys _FA9A2FC8130449AA328C19ACD9506C2D)。反应,_UL_PetrovLeonid.WhatIsIsideResponseNewsFeed。(CodingKeys _FA9A2FC8130449AA328C19ACD9506C2D)。项目,基金会。(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue:“Index 0”,intValue: Optional(0)), debugDescription:“没有与关键附件相关的值(\“附件\”)。underlyingError:nil))

Why is that happening and what do I need to do to solve it? I've been into coding only three months from now, so please forgive me beforehand if my problem seems silly.

为什么会这样,我需要做什么来解决它?从现在开始我才开始写代码三个月,所以如果我的问题看起来很愚蠢,请先原谅我。

Thank you.

谢谢你!

1 个解决方案

#1


1  

The error message is very clear

错误信息非常清晰

... Swift.DecodingError.keyNotFound ... NewsItems.(CodingKeys in _FA9A2FC8130449AA328C19ACD9506C2D).attachments ... No value associated with key attachments (\"attachments\").

…Swift.DecodingError。keyNotFound……NewsItems。(CodingKeys _FA9A2FC8130449AA328C19ACD9506C2D)。附件……没有与键附件相关的值(\“附件\”)。

  • keyNotFound is key is missing
  • key notfound是key is missing
  • NewsItems.(CodingKeys ... ).attachments is the object for key attachments in NewsItems which is Attachments
  • NewsItems。(CodingKeys……)。附件是NewsItems中的关键附件的对象,它是附件
  • No value associated with key attachments (\"attachments\") is what is says.
  • 没有与关键附件相关的值(“附件\”)是这样说的。

Shortly: There is no key attachments in Attachments which is true.

简而言之:附件中没有真实的关键附件。

Look at your JSON

看看你的JSON

      "attachments": [
            {
                "type": "photo",
                "photo": {

The class equivalent is

等效的类是

class Attachments: Decodable {
    let type : String
    let photo : AttachmentPhoto
}

And AttachmentPhoto is supposed to be

附件照片应该是

class AttachmentPhoto: Decodable {

    private enum CodingKeys : String, CodingKey {
        case photo604 = "photo_604"
        case id
    }

    let id : Int
    let photo604 : String // or even URL
    // etc.
}

Actually there is no need to use classes, in most cases a struct is sufficient.

实际上,不需要使用类,在大多数情况下,一个struct就足够了。

#1


1  

The error message is very clear

错误信息非常清晰

... Swift.DecodingError.keyNotFound ... NewsItems.(CodingKeys in _FA9A2FC8130449AA328C19ACD9506C2D).attachments ... No value associated with key attachments (\"attachments\").

…Swift.DecodingError。keyNotFound……NewsItems。(CodingKeys _FA9A2FC8130449AA328C19ACD9506C2D)。附件……没有与键附件相关的值(\“附件\”)。

  • keyNotFound is key is missing
  • key notfound是key is missing
  • NewsItems.(CodingKeys ... ).attachments is the object for key attachments in NewsItems which is Attachments
  • NewsItems。(CodingKeys……)。附件是NewsItems中的关键附件的对象,它是附件
  • No value associated with key attachments (\"attachments\") is what is says.
  • 没有与关键附件相关的值(“附件\”)是这样说的。

Shortly: There is no key attachments in Attachments which is true.

简而言之:附件中没有真实的关键附件。

Look at your JSON

看看你的JSON

      "attachments": [
            {
                "type": "photo",
                "photo": {

The class equivalent is

等效的类是

class Attachments: Decodable {
    let type : String
    let photo : AttachmentPhoto
}

And AttachmentPhoto is supposed to be

附件照片应该是

class AttachmentPhoto: Decodable {

    private enum CodingKeys : String, CodingKey {
        case photo604 = "photo_604"
        case id
    }

    let id : Int
    let photo604 : String // or even URL
    // etc.
}

Actually there is no need to use classes, in most cases a struct is sufficient.

实际上,不需要使用类,在大多数情况下,一个struct就足够了。