简体   繁体   中英

Can't access data from a nested array in a JSON in swift

I have a JSON with a nested array, I'd like to access one of the data contained in that nested array, but I have no idea how I could do that.

I'm developing an IOS App and try to parse some data from a (local for now) JSON. I want to display some of the data to the user.

This is what my JSON looks like:

{
"format": "json",
"data": [
    {
        "type": "channel",
        "id": "789",
        "updated_at": "2019-05-03 11:32:57",
        "unread_count": 3,
        "title": "title",
        "context": "search",
        "relationships": {
            "recipients": [
                {
                    "type": "user",
                    "rating": 5,
                    "is_spotlighted": false,
                    "id": 123,
                    "participant_id": 456
                }
            ],
        }
    }
}

for now I access the different value with:

struct Root: Decodable {
    let format: String
    let data: [ChannelData]
}

struct ChannelData: Decodable {
    let title, type, id, context, updatedAt: String
    let unreadCount: Int
    let relationships: Relationships
}

struct Relationships: Decodable {
    let recipients: [Recipient]
}

struct Recipient: Decodable {
    let type: String
    let id: Int
    let participantId: Int
    let isSpotlighted: Bool
    let rating: Double
}

The data I want to access to is "rating"

This is what my viewDidLoad() looks like :

var chatList = [ChannelData]()

override func viewDidLoad() {

    super.viewDidLoad()
    let url = Bundle.main.url(forResource: "channels", withExtension: "json")!
    let data = try! Data(contentsOf: url)
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let result = try! decoder.decode(Root.self, from: data)
    chatList = result.data
    self.tableView.reloadData()
}

When in another function I try to access to the rating through:

let currentChat = chatList[indexPath.row]
cell.Name.text = currentChat.relationships.recipients

Nothing is shown when I try to get other parameters after .recipients. I'm a beginner using JSON and more or less using Swift too.

Relationships contains one property recipients with the type [Recipient] . You could use .first to access the first Recipient object from the array. Then you can get any property from Recipient object

cell.Name.text = currentChat.relationships.recipients.first?.rating

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM