Home > Software design >  Swift JSON Parsing issue - Possible problem with struct?
Swift JSON Parsing issue - Possible problem with struct?

Time:08-29

Upon login and validation, the user is sent to the main application page. I have the following code set.

import SwiftUI

typealias MyDefendant = [Defendant]
struct ContentView: View {
    var email: String
    @State var myDefendant: MyDefendant = []

    func getUserData(completion:@escaping (MyDefendant)->()) {
        
        var urlRequest = URLRequest(url: URL(string: "https://milanobailbonds.com/getDefendant.php")!)
        urlRequest.httpMethod = "post"
        
        let authData = [
            "defEmail" : email
            
            ] as [String : Any]
        
        do {
            let authBody = try JSONSerialization.data(withJSONObject: authData, options: .prettyPrinted)
            
            urlRequest.httpBody = authBody
            urlRequest.addValue("application/json", forHTTPHeaderField: "content-type")
           
        } catch let error {
            debugPrint(error.localizedDescription)
        }
        
        URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
            if let error = error {
                print(error.localizedDescription)
                return
            }
            guard let data = data else {
                return
            }
            do {
            let responseString = String(data: data, encoding: .utf8)!
                print(responseString)
            var returnValue: MyDefendant?
            let decoder = JSONDecoder()
                
            returnValue = try decoder.decode([Defendant].self, from: data)
            completion(returnValue!)
            }
            catch { fatalError("Couldn't Parse")
                
            }
        }.resume()
    return
        
        
        
    }
    
    
    
    var body: some View {
        
        NavigationView {
        
            VStack {
               
            Text(email)
            Text("I Need Bail")
                .font(.largeTitle)
                .fontWeight(.semibold)
         
        Button {
            print("Test")
        } label: {
            Label("I Need Bail", systemImage: "iphone.homebutton.radiowaves.left.and.right")
            .labelStyle(IconOnlyLabelStyle())
            .font(.system(size: 142.0))
            
            
        }

        }    .foregroundColor(.green)
            .shadow(color: .black, radius: 2, x: 2, y: 2)
            .navigationBarTitle("Home")
            .navigationBarTitleDisplayMode(.inline)
               .navigationBarItems(leading:
                Button {
                  print("Test")
               } label: {
                   Label("I Need Bail", systemImage: "line.3.horizontal")
                   .labelStyle(IconOnlyLabelStyle())
                   
                   
               })

        }.onAppear() {
            getUserData() { myDefendant in
                self.myDefendant = myDefendant
                
            }
        }
        
                
          
            
        }
    }

In my data models I have created a struct for Defendant as such:

struct Defendant: Codable, Hashable, Identifiable {
    var id: Int
    var defImage: String
    var defName: String
    var defAddress: String
    var defCity: String
    var defState: String
    var defZip: String
    var defPhone: String
    var defEmail: String
    var defUserName: String
    var defPW: String
    var defDOB: String
    var defPriorFTA: Int
    var defFTAExplained: String
    var defAssignedAgency: Int
    
} // Defendant Model

The PHP is working fine and returning valid JSON with all of the required items for the struct.

"\"[\\n    {\\n        \\\"Id\\\": 5,\\n        \\\"defImage\\\": \\\"\\\",\\n        \\\"defName\\\": \\\"Some Dude\\\",\\n        \\\"defAddress\\\": \\\"123 Main St\\\",\\n        \\\"defCity\\\": \\\"Some City\\\",\\n        \\\"defState\\\": \\\"FL\\\",\\n        \\\"defZip\\\": \\\"12345\\\",\\n        \\\"defPhone\\\": \\\"888-888-8888\\\",\\n        \\\"defEmail\\\": \\\"[email protected]\\\",\\n        \\\"defUserName\\\": \\\"\\\",\\n        \\\"defPW\\\": \\\"91492cffa4032765f6b025ec6b2c873e49fe5e58\\\",\\n        \\\"defDOB\\\": \\\"01\\\\\\/01\\\\\\/1955\\\",\\n        \\\"defPriorFTA\\\": 0,\\n        \\\"defFTAExplained\\\": \\\"\\\",\\n        \\\"defAssignedAgency\\\": 0\\n    }\\n]\""   

Unfortunately, I keep getting an error "Unable to Parse".

I'm new to Swift, and coding in general. Any thoughts or ideas are greatly appreciated.

Thank you

CodePudding user response:

Im not sure but you can try to change id into Id in your struct. Please remember name of your struct property must exactly the same with key in Json response.

  • Related