/ / स्विफ्ट के साथ विशिष्ट JSON को डीकोड / पार्स करना - ios, json, स्विफ्ट

स्विफ्ट के साथ विशिष्ट जेएसओएन डीकोडिंग / पार्सिंग - आईओएस, जेसन, स्विफ्ट

मुझे स्विफ्ट 4 के साथ इस JSON को डिकोड करने में बहुत परेशानी हो रही है।

{
"Items": [
{
"id": 1525680450507,
"animal": "bee",
"type": "insect",
"diet": [
"a",
"b",
"c"
]
}
],
"Count": 1,
"ScannedCount": 5
}

यहाँ मैं डिकोड करने की कोशिश करता हूँ

let decoder = JSONDecoder()
let data = try decoder.decode([Animal].self, from: data)

मैंने इस तरह का एक स्ट्रक्चर बनाया है

struct Animal: Codable {
var id: Int
var animal: String
var type: String
var diet: [String]
}

let decoder = JSONDecoder()
let data = try decoder.decode(ItemsResponse.self, from: data)

यह काम नहीं करता है। मुझे एक त्रुटि मिलती है जो कहती है

"ऐरे को डिकोड करने की उम्मीद <कोई> लेकिन इसके बजाय एक शब्दकोश मिला।"

इसलिए मुझे लगा कि शायद मुझे कुछ इस तरह की जरूरत है

struct ItemsResponse: Codable {
var Items: [Animal]
var Count: Int
var ScannedCount: Int
}

लेकिन यह या तो काम नहीं करता है

"ऐरे को डीकोड करने की उम्मीद <कोई> लेकिन इसके बजाय एक स्ट्रिंग / डेटा मिला।"

मैं एक संरचना कैसे बनाऊंगा जो इस JSON को डिकोड करेगा?

उत्तर:

जवाब के लिए 0 № 1
let data = try decoder.decode([Animal].self, from: data)

[Animal].self सही नहीं है आप इसे इस तरह से उपयोग कर सकते हैं:

struct DataJson: Codable {
let items: [Item]
let count, scannedCount: Int

enum CodingKeys: String, CodingKey {
case items = "Items"
case count = "Count"
case scannedCount = "ScannedCount"
}
}

struct Item: Codable {
let id: Int
let animal, type: String
let diet: [String]
}

// MARK: Convenience initializers

extension DataJson {
init(data: Data) throws {
self = try JSONDecoder().decode(DataJson.self, from: data)
}



func jsonData() throws -> Data {
return try JSONEncoder().encode(self)
}

func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}

extension Item {
init(data: Data) throws {
self = try JSONDecoder().decode(Item.self, from: data)
}


func jsonData() throws -> Data {
return try JSONEncoder().encode(self)
}

func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}

जवाब के लिए 0 № 2

इसे इस्तेमाल करे:

import Foundation

let json = """
{
"Items": [
{
"id": 1525680450507,
"animal": "bee",
"type": "insect",
"diet": [
"a",
"b",
"c"
]
}
],
"Count": 1,
"ScannedCount": 5
}
"""

struct Animal: Codable {
var id: Int
var animal: String
var type: String
var diet: [String]
}

struct ItemsResponse: Codable {
var Items: [Animal]
var Count: Int
var ScannedCount: Int
}

let data = try! JSONDecoder().decode(ItemsResponse.self, from: json.data(using: .utf8)!)

बेशक, आपको संभावित विफलताओं (यानी डॉन "टी को ठीक से संभालना चाहिए try!, और डॉन "टी बल-अलंकृत json.data()! अंश)

लेकिन ऊपर दिया गया कोड काम करता है और आपके प्रश्न का उत्तर देता है।