Reputation: 389
Here is my code to get complete Json;
var str = "Hello"
var dictionary = ["key1":"val1", "key2":"val2", "key3":"val3"]
var products = [Product]()
struct Product: Codable {
var title: String
var reference: String
}
func createProducts(title: String, refer: String) {
products.append(Product(title: title, reference: refer))
}
for element in dictionary {
createProducts(title: element.key, refer: element.value)
}
var general = [str: products]
let encodedData = try? JSONEncoder().encode(general)
let json = String(data: encodedData!, encoding: .utf8)!
print(json)
My Json dict is as follows;
{"Hello":[{"title":"key2","reference":"val2"},{"title":"key3","reference":"val3"},{"title":"key1","reference":"val1"}]}
and after decoding of Json, i only need to get this part;
[{"title":"key2","reference":"val2"},{"title":"key3","reference":"val3"},{"title":"key1","reference":"val1"}]
i have issue with decoder below, to get value of "Hello";
if let decodedData = try! JSONDecoder().decode(general.self, from: json.data(using: .utf8)!) {
print(decodedData)
}
Upvotes: 0
Views: 1514
Reputation: 285069
The actual type of the encoded JSON is [String:[Product]]
so decode that and get the value for Hello
do {
let decodedData = try JSONDecoder().decode([String:[Product]].self, from: Data(json.utf8))
print(decodedData["Hello"]!)
} catch {
print(error)
}
Alternatively create an umbrella Root
struct
struct Root : Decodable {
private enum CodingKeys : String, CodingKey { case hello = "Hello" }
let hello : [Product]
}
and decode that
do {
let decodedData = try JSONDecoder().decode(Root.self, from: Data(json.utf8))
print(decodedData.hello)
Upvotes: 2