deal with deep nested json in swift decodable - json

I have this deep nested JSON:
{
"response": {
"status": {
"status_code": 200,
"execute_time": 0.0068638324737549
},
"list": {
"beers": [
{
"beer": {
"id": 323,
"name": "Saint Arnold",
"style": "IPA"
}
},
{
"beer": {
"id": 873,
"name": "Black Angel",
"style": "Stout"
}
},
]
}
}
}
I would like to create just a struct like:
struct Beer {
let id: Int
let name: String
let style: String
init(from decoder: Decoder) throws {
... custom decode ...
}
}
and make a custom decode to decode from json just to this model and not to create a struct for every level of the json.
I don't know where to start, someone could help?
I tried to play with container.encode() but I can't understand how it's work in my case.

Related

Stuck Decoding Multidimensional JSON From URLSession

I have been stuck for a few days trying to decode a multidimensional JSON array from a URLSession call. This is my first project decoding JSON in SwiftUI. My attempts from reading up on methods others suggest do not seem to work.
Here is my JSON response from the server
"success": true,
"message": "Authorized",
"treeData": {
"Right": {
"G1P1": {
"Name": "John Johnson",
"ID": 387,
"SubText": "USA 2002"
},
"G2P1": {
"Name": "Tammy Johnson",
"ID": 388,
"SubText": "USA 2002"
},
"G2P2": {
"Name": "Susan Johnson",
"ID": 389,
"SubText": "USA 1955"
}
},
"Left": {
"G1P1": {
"Name": "Jane Doe",
"ID": 397,
"SubText": "USA 2002"
},
"G2P1": {
"Name": "John Doe",
"ID": 31463,
"SubText": "USA 2002"
},
"G2P2": {
"Name": "Susan Doe",
"ID": 29106,
"SubText": "USA 1958"
}
}
}
}
Here is my decode block of code
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data, error == nil else {
completion(.failure(.noData))
return
}
guard let treeResponse = try? JSONDecoder().decode([String: TreeResponse].self, from: data) else {
completion(.failure(.decodingError))
return
}
dump(treeResponse)
completion(.success("Hooray"))
}.resume()
And then here are my structs, which is the part I can't seem to figure out
struct TreeResponse: Codable {
let success: Bool
let message: String
let treeData: [String:SideData]
}
struct SideData: Codable {
let personKey: [String:PersonInfo]
}
struct PersonInfo: Codable {
let Name: String
let ID: Int
let SubText: String
}
My hope is to be able to access the decoded data as treeResponse.Right.G1P1.Name
Could really use help moving past this
I will post this as an answer even if it cannot be one, but that way I can at least format it properly :-).
First of all you should learn to pose your questions in a manner that makes it as easy as possible for anyone to execute your code. Swift has a particularly helpful way of doing this, you can run a Playground on it. Then you should start whittling down your question to its essence which appears to be the JSON decode. JSONDecoder usually is very helpful in providing you with decent error messages on what it does not like about your JSON, but you have to print them. A suitable Playground would look as follows:
import UIKit
let jsonStr = """
{
"success": true,
"message": "Authorized",
"treeData": {
"Right": {
"G1P1": {
"Name": "John Johnson",
"ID": 387,
"SubText": "USA 2002"
},
"G2P1": {
"Name": "Tammy Johnson",
"ID": 388,
"SubText": "USA 2002"
},
"G2P2": {
"Name": "Susan Johnson",
"ID": 389,
"SubText": "USA 1955"
}
},
"Left": {
"G1P1": {
"Name": "Jane Doe",
"ID": 397,
"SubText": "USA 2002"
},
"G2P1": {
"Name": "John Doe",
"ID": 31463,
"SubText": "USA 2002"
},
"G2P2": {
"Name": "Susan Doe",
"ID": 29106,
"SubText": "USA 1958"
}
}
}
}
"""
struct TreeResponse: Codable {
let success: Bool
let message: String
let treeData: [String:SideData]
}
struct SideData: Codable {
let personKey: [String:PersonInfo]
}
struct PersonInfo: Codable {
let Name: String
let ID: Int
let SubText: String
}
let jsonData = jsonStr.data(using:.utf8)!
do {
let tree = try JSONDecoder().decode(TreeResponse.self, from: jsonData)
print(tree)
} catch {
print(tree)
}
This will yield a somewhat descriptive error message:
keyNotFound(CodingKeys(stringValue: "personKey", intValue: nil),
Swift.DecodingError.Context(codingPath:
[CodingKeys(stringValue: "treeData", intValue: nil),
_JSONKey(stringValue: "Right", intValue: nil)],
debugDescription: "No value associated with key
CodingKeys(stringValue: \"personKey\", intValue: nil)
(\"personKey\").", underlyingError: nil))
(Indentation mine and not particularly well thought out)
This starts pointing out your problems (of which you still seem to have a lot).
The first level of decode is somewhat ok, but the second level is woefully inadequate in its current form. There is no such thing as a personKey in your JSON which would be required to fit it into a simple struct. However you still might be able to coax it through some decode method.
Considering you JSON that appears to be a bad choice and you should opt for properly modelling your tree with the given Left and Right keys, although this is probably scratching the limit of what Decodable will do for you for free, so you will have to put in some more work to get this to work on a more involved example. If the keys on the following levels have any special significance you will have to put in a special decode there too.
In any way, you should definitely learn to formulate your questions better.
when our structure are not perfect to JSON so that's why get this types error and i've use JSONDecoder to retrieve the data from JSON couldn't read the data it's missing, though, such error yet get so needs to create quite perfect JSON models or create model with CodingKeys such like:
struct JSONData: Codable {
let success: Bool
let message: String
let treeData: TreeData
}
struct TreeData: Codable {
let treeDataRight, treeDataLeft: [String: Left]
enum CodingKeys: String, CodingKey {
case treeDataRight = "Right"
case treeDataLeft = "Left"
}
}
struct Left: Codable {
let name: String
let id: Int
let subText: String
enum CodingKeys: String, CodingKey {
case name = "Name"
case id = "ID"
case subText = "SubText"
}
}
For get JSON data to need JSONDecoder():
let jsonData = jsonStr.data(using:.utf8)!
do {
let tree = try JSONDecoder().decode(JSONData.self, from: jsonData)
dump(tree)
} catch {
print(error.localizedDescription)
}
Together with json, JSON model, JSONDecoder():
let jsonStr = """
{
"success": true,
"message": "Authorized",
"treeData": {
"Right": {
"G1P1": {
"Name": "John Johnson",
"ID": 387,
"SubText": "USA 2002"
},
"G2P1": {
"Name": "Tammy Johnson",
"ID": 388,
"SubText": "USA 2002"
},
"G2P2": {
"Name": "Susan Johnson",
"ID": 389,
"SubText": "USA 1955"
}
},
"Left": {
"G1P1": {
"Name": "Jane Doe",
"ID": 397,
"SubText": "USA 2002"
},
"G2P1": {
"Name": "John Doe",
"ID": 31463,
"SubText": "USA 2002"
},
"G2P2": {
"Name": "Susan Doe",
"ID": 29106,
"SubText": "USA 1958"
}
}
}
}
"""
struct JSONData: Codable {
let success: Bool
let message: String
let treeData: TreeData
}
struct TreeData: Codable {
let treeDataRight, treeDataLeft: [String: Left]
enum CodingKeys: String, CodingKey {
case treeDataRight = "Right"
case treeDataLeft = "Left"
}
}
struct Left: Codable {
let name: String
let id: Int
let subText: String
enum CodingKeys: String, CodingKey {
case name = "Name"
case id = "ID"
case subText = "SubText"
}
}
let jsonData = jsonStr.data(using:.utf8)!
do {
let tree = try JSONDecoder().decode(JSONData.self, from: jsonData)
dump(tree)
} catch {
print(error.localizedDescription)
}
Result:
Result here
and i hope this would work and helpfully so try once

Cannot convert value of type '[Surah]' to expected argument type 'Range<Int>'

hi Guys
i try to learn swift, i need your help
i try to connect json with swift i get errors
Cannot convert value of type '[Surah]' to expected argument type 'Range'
thank you vor the help
struct Surah: Codable {
struct Juz: Codable {
let index: String
let verse: Verse
}
struct Verse: Codable {
let start, end: String
}
enum Place: String, Codable {
case mecca = "Mecca"
case medina = "Medina"
}
enum TypeEnum: String, Codable {
case madaniyah = "Madaniyah"
case makkiyah = "Makkiyah"
}
let place: Place
let type: TypeEnum
let count: Int
let title, titleAr, index, pages: String
let juz: [Juz] }
/***************/
struct ContentView: View {
let surahs: [Surah] = Bundle.main.decode("source/surah.json")
var body: some View {
NavigationView{
List{
ForEach(surahs){section in
Section(header:Text(section.title)){
ForEach(section.juz, id: \.verse){juzs in
Text(juzs.verse.start)
}
}
}
}
}
}
}
JSON:
[{
"place": "Mecca",
"type": "Makkiyah",
"count": 7,
"title": "Al-Fatiha",
"titleAr":"الفاتحة",
"index": "001",
"pages": "1",
"juz": [
{
"index": "01",
"verse": {
"start": "verse_1",
"end": "verse_7"
}
}
]
},
{
"place": "Medina",
"type": "Madaniyah",
"count": 286,
"title": "Al-Baqara",
"titleAr":"البقرة",
"index": "002",
"pages": "2",
"juz": [
{
"index": "01",
"verse": {
"start": "verse_1",
"end": "verse_141"
}
},
{
"index": "02",
"verse": {
"start": "verse_142",
"end": "verse_252"
}
},
{
"index": "03",
"verse": {
"start": "verse_253",
"end": "verse_286"
}
}
]
}]
I'm trying to create forEach method for horizontal collection for properties
how can i call this part of json??
I hope someone can help me..
now i need to call second Json part in my Swift
{
"index": "001",
"name": "al-Fatihah",
"verse": {
"verse_1": "بِسْمِ ٱللَّهِ ٱلرَّحْمَٰنِ ٱلرَّحِيمِ",
"verse_2": "ٱلْحَمْدُ لِلَّهِ رَبِّ ٱلْعَٰلَمِينَ",
"verse_3": "ٱلرَّحْمَٰنِ ٱلرَّحِيمِ",
"verse_4": "مَٰلِكِ يَوْمِ ٱلدِّينِ",
"verse_5": "إِيَّاكَ نَعْبُدُ وَإِيَّاكَ نَسْتَعِينُ",
"verse_6": "ٱهْدِنَا ٱلصِّرَٰطَ ٱلْمُسْتَقِيمَ",
"verse_7": "صِرَٰطَ ٱلَّذِينَ أَنْعَمْتَ عَلَيْهِمْ غَيْرِ ٱلْمَغْضُوبِ عَلَيْهِمْ وَلَا ٱلضَّآلِّينَ"
},
"count": 7,
"juz": [
{
"index": "01",
"verse": {
"start": "verse_1",
"end": "verse_7"
}
}
]
}
how can I call it up and code it? or formatting
struct ContentView: View {
let surahs: [Surah] = Bundle.main.decode("source/surah.json")
var body: some View {
NavigationView{
List{
ForEach(surahs, id:\. index){section in
Section(header:Text(section.title)){
ForEach(section.juz, id: \.verse){juzs in
Text(juzs.verse.start)
}
}
}
}
}
}

How do you parse recursive JSON in Swift?

I am receiving JSON from a server where the data is recursive. What is the best way to parse this into a convenient Swift data structure?
Defining a Swift Codable data structure to parse it into fails because the recursive properties are not allowed.
The Swift compiler reports: "Value type 'FamilyTree.Person' cannot have a stored property that recursively contains it"
{
"familyTree": {
"rootPerson": {
"name": "Tom",
"parents": {
"mother": {
"name": "Ma",
"parents": {
"mother": {
"name": "GraMa",
"parents": {}
},
"father": {
"name": "GraPa",
"parents": {}
}
}
},
"father": {
"name": "Pa",
"parents": {}
}
}
}
}
}
Ideally the end result would be a bunch of person objects pointing to their mother and father objects starting from a rootPerson object.
The first thought is to create structs such as:
struct Person: Codable {
var name: String
var parents: Parents
}
struct Parents: Codable {
var mother: Person?
var father: Person?
}
But this doesn't work since you can't have recursive stored properties like this.
Here is one possible working solution:
let json = """
{
"familyTree": {
"rootPerson": {
"name": "Tom",
"parents": {
"mother": {
"name": "Ma",
"parents": {
"mother": {
"name": "GraMa",
"parents": {}
},
"father": {
"name": "GraPa",
"parents": {}
}
}
},
"father": {
"name": "Pa",
"parents": {}
}
}
}
}
}
"""
struct Person: Codable {
var name: String
var parents: [String: Person]
}
struct FamilyTree: Codable {
var rootPerson: Person
}
struct Root: Codable {
var familyTree: FamilyTree
}
let decoder = JSONDecoder()
let tree = try decoder.decode(Root.self, from: json.data(using: .utf8)!)
print(tree)
In a playground this will correctly parse the JSON.
The parents dictionary of Person will have keys such as "mother" and "father". This supports a person have any number of parents with any role.
Possible implementation using classes.
(Swift 5 synthesizes default initializers for classes. Dont remember if so for Swift 4)
import Foundation
var json: String = """
{
"familyTree": {
"rootPerson": {
"name": "Tom",
"parents": {
"mother": {
"name": "Ma",
"parents": {
"mother": {
"name": "GraMa",
"parents": {}
},
"father": {
"name": "GraPa",
"parents": {}
}
}
},
"father": {
"name": "Pa",
"parents": {}
}
}
}
}
}
"""
final class Parents: Codable{
let mother: Person?
let father: Person?
}
final class Person: Codable{
let name: String
let parents: Parents?
}
final class RootPerson: Codable {
var rootPerson: Person
}
final class Root: Codable {
var familyTree: RootPerson
}
var jsonData = json.data(using: .utf8)!
do{
let familyTree = try JSONDecoder().decode(Root.self, from: jsonData)
print("Ma •••>", familyTree.familyTree.rootPerson.parents?.mother?.name)
print("GraPa •••>", familyTree.familyTree.rootPerson.parents?.mother?.parents?.father?.name)
print("Shoud be empty •••>", familyTree.familyTree.rootPerson.parents?.mother?.parents?.father?.parents?.father?.name)
} catch {
print(error)
}

Parsing nested JSON using Decodable's init(from decoder:)

I'm decoding JSON using Decodable with init(from decoder:) but unable to parse out my nested JSON.
The JSON I'm trying to parse:
The main conflict I believe is parsing the array of edges.
The goal is to get a model I can use with key, value, and namespace.
Would need to use init(from decoder:).
{
"data": {
"collectionByHandle": {
"metafields": {
"edges": [
{
"node": {
"key": "city",
"value": "Fayetteville ",
"namespace": "shipping"
}
},
{
"node": {
"key": "country",
"value": "United States",
"namespace": "shipping"
}
},
{
"node": {
"key": "state",
"value": "AR",
"namespace": "shipping"
}
}
]
}
}
},
"errors": null
}
This technically works but wanting to use init(from decoder: ) and return a model that just has key, value, and namespace without having multiple separate structs/classes.
struct Shipping: Codable {
let data: DataClass
let errors: String?
}
struct DataClass: Codable {
let collectionByHandle: CollectionByHandle
}
struct CollectionByHandle: Codable {
let metafields: Metafields
}
struct Metafields: Codable {
let edges: [Edge]
}
struct Edge: Codable {
let node: Node
}
struct Node: Codable {
let key, value, namespace: String
}

How to create Struct for more then one json table in swift xcode

I am writing an IOS Application that need to read a JSON FIle.
I understood the best way to do that is to write a struct for that json file and parse the json into that struct to be able to use freely.
I have a Json file that is saved locally in one of the folders
{
"colors": [
{
"color": "black",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,255,255,1],
"hex": "#000"
}
},
{
"color": "white",
"category": "value",
"code": {
"rgba": [0,0,0,1],
"hex": "#FFF"
}
},
{
"color": "red",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,0,0,1],
"hex": "#FF0"
}
},
{
"color": "blue",
"category": "hue",
"type": "primary",
"code": {
"rgba": [0,0,255,1],
"hex": "#00F"
}
},
{
"color": "yellow",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,255,0,1],
"hex": "#FF0"
}
},
{
"color": "green",
"category": "hue",
"type": "secondary",
"code": {
"rgba": [0,255,0,1],
"hex": "#0F0"
}
},
],
"people": [
{
"first_name": "john",
"is_valid": true,
"friends_list": {
"friend_names": ["black", "hub", "good"],
"age": 13
}
},
{
"first_name": "michal",
"is_valid": true,
"friends_list": {
"friend_names": ["jessy", "lyn", "good"],
"age": 19
}
},
{
"first_name": "sandy",
"is_valid": false,
"friends_list": {
"friend_names": ["brown", "hub", "good"],
"age": 15
}
},
]
}
i created a struct for each one of the two tables:
import Foundation
struct Color {
var color: String
var category: String
var type: String
var code: [JsonCodeStruct]
}
struct Poeople {
var firsName: String
var is_valid: Bool
var friendsNames: [JsonFriendNames]
}
struct JsonFriendNames {
var friendNames: [String]
var age: String
}
struct JsonCodeStruct {
var rgba: [Double]
var hex: String
}
and I want to open the local json file
and assign it the structs that I gave and then read them easily in the code.
can you suggest me a way on how to do that?
First of all you need an umbrella struct to decode the colors and people keys
struct Root: Decodable {
let colors: [Color]
let people : [Person]
}
The types in your structs are partially wrong. The Color related structs are
struct Color: Decodable {
let color: String
let category: String
let type: String?
let code : ColorCode
}
struct ColorCode: Decodable {
let rgba : [UInt8]
let hex : String
}
and the Person related structs are
struct Person: Decodable {
let firstName : String
let isValid : Bool
let friendsList : Friends
}
struct Friends: Decodable {
let friendNames : [String]
let age : Int
}
Assuming you read the file with
let data = try Data(contentsOf: URL(fileURLWithPath:"/...."))
you can decode the JSON into the given structs with
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
let result = try decoder.decode(Root.self, from: data)
print(result)
} catch { print(error) }