Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON not parsing properly

Tags:

json

ios

swift

I tried to parse a JSON file and when I parse it as per the syntax, it gives me an error that cannot change the string to an array of dictionary, but when I fix the problem, it generates nil. Can anyone give an opinion?

func jsonFour() {
    let string = "[{\"address\": 7023000630,\"reportStatus\": \"Retrieved\",\"currentLocation\": {\"latitude\": 29.8529, \"longitude\": 73.99332,\"timestamp\": \"2019-01-07T16:35:25.079+05:30\"} }, {\"address\": 7290098339, \"reportStatus\": \"Retrieved\", \"currentLocation\": {\"latitude\": 21.628569, \"longitude\": 72.996956,\"timestamp\": \"2019-01-07T16:35:25.079+05:30\" } } ]"
    
    let data = string.data(using: .utf8)!
    do {
        if let jsonArray = try JSONSerialization.jsonObject(with: data, options : JSONSerialization.ReadingOptions.mutableContainers) as? [[ String : Any ]]
        {
            print(jsonArray) // use the json here
            let address = jsonArray["address"] as! [[String:Any]]
            if let timestamp = address["timestamp"] as? [String]{print(timestamp)}
        } else {
            print("bad json")
        }
    } catch let error as NSError {
        print(error)
    }

}

When I remove the double brackets from "String : Any", it runs fine, but does not give any value but nil.

And when I proceed with this way, it skips the if statement and just prints:

"bad json".

What am I doing wrong here?

like image 884
vgvishesh23113 Avatar asked Nov 15 '25 18:11

vgvishesh23113


2 Answers

Since there is Codable, I would strongly recommend you to using it instead of JSONSerialization.

So start with declaring your structs to match with your JSON struct

struct Model: Codable {
    var address: Int
    var reportStatus: String
    var currentLocation: Location
}

struct Location: Codable {
    var latitude, longitude: Double
    var timestamp: String
}

Now just decode your JSON using JSONDecoder

do {
    let data = string.data(using: .utf8)!
    let models = try JSONDecoder().decode([Model].self, from: data)
} catch {
    print(error)
}

... now models is array of Model objects and you can work with it.

like image 127
Robert Dresler Avatar answered Nov 18 '25 09:11

Robert Dresler


In your code snippet jsonArray is an array and array can't subscript a value of type [[String: Any]], so instead you should parse like,

func jsonFour(){
    let string = "[{\"address\": 7023000630,\"reportStatus\": \"Retrieved\",\"currentLocation\": {\"latitude\": 29.8529, \"longitude\": 73.99332,\"timestamp\": \"2019-01-07T16:35:25.079+05:30\"} }, {\"address\": 7290098339, \"reportStatus\": \"Retrieved\", \"currentLocation\": {\"latitude\": 21.628569, \"longitude\": 72.996956,\"timestamp\": \"2019-01-07T16:35:25.079+05:30\" }}]"

    let data = string.data(using: .utf8)!
    do {
        if let jsonArray = try JSONSerialization.jsonObject(with: data, options : JSONSerialization.ReadingOptions.mutableContainers) as? [[String: Any]]
        {
            print(jsonArray) // print the json here
            for jsonObj in jsonArray {
                if let dict = jsonObj as? [String: Any] {
                    if let address = dict["address"] {
                        print(address)
                    }
                    if let location = dict["currentLocation"] as? [String: Any], let timeStamp = location["timestamp"]  {
                        print(timeStamp)
                    }
                }
            }
        } else {
            print("bad json")
        }
    } catch let error as NSError {
        print(error)
    }
}
like image 22
Bappaditya Avatar answered Nov 18 '25 08:11

Bappaditya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!