json array shows in debugger but can't parse (corrected question)

Hello,

Please see the test project at https://we.tl/t-aWAu7kk9lD

I have a json array showing in Xcode debugger (from the line "print(dataString)"):

Optional("[{\"id\":\"8e8tcssu4u2hn7a71tkveahjhn8xghqcfkwf1bzvtrw5nu0b89w\",\"name\":\"Test name 0\",\"country\":\"Test country 0\",\"type\":\"Test type 0\",\"situation\":\"Test situation 0\",\"timestamp\":\"1546848000\"},{\"id\":\"z69718a1a5z2y5czkwrhr1u37h7h768v05qr3pf1h4r4yrt5a68\",\"name\":\"Test name 1\",\"country\":\"Test country 1\",\"type\":\"Test type 1\",\"situation\":\"Test situation 1\",\"timestamp\":\"1741351615\"},{\"id\":\"fh974sv586nhyysbhg5nak444968h7hgcgh6yw0usbvcz9b0h69\",\"name\":\"Test name 2\",\"country\":\"Test country 2\",\"type\":\"Test type 2\",\"situation\":\"Test situation 2\",\"timestamp\":\"1741351603\"},{\"id\":\"347272052385993\",\"name\":\"Test name 3\",\"country\":\"Test country 3\",\"type\":\"Test type 3\",\"situation\":\"Test situation 3\",\"timestamp\":\"1741351557\"}]")

But my JSON decoder is throwing a catch error

Line 57, Error in JSON parsing
typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

This is the code:

let urlString = "https://www.notafunnyname.com/jsonmockup.php"
        let url = URL(string: urlString)
        
        guard url != nil else {
            return
        }
        
        let session = URLSession.shared
        
        let dataTask = session.dataTask(with: url!) { (data, response, error) in
           
            var dataString = String(data: data!, encoding: String.Encoding.utf8)
            print(dataString)
            
            if error == nil && data != nil {
                // Parse JSON
                let decoder = JSONDecoder()
                
                do {
                    
                        let newsFeed = try decoder.decode(NewsFeed.self, from: data!)
                            
                            print("line 51")
                            print(newsFeed)
                            print(error)
                            
                        }
                        catch{
                            print("Line 57, Error in JSON parsing")
                            print(error)
                        }
                
            }
        }
        
        // Make the API Call
        dataTask.resume()
    }

And this is my Codable file NewsFeed.swift:

struct NewsFeed: Codable {
    
    var id: String
    var name: String
    var country: String
    var type: String
    var situation: String
    var timestamp: String
    
}

Please do you know how to resolve the typeMismatch error?

That's because your JSON is an array. Look:

[  <--- BEGIN ARRAY
	{
		"id": "8e8tcssu4u2hn7a71tkveahjhn8xghqcfkwf1bzvtrw5nu0b89w",
		"name": "Test name 0",
		"country": "Test country 0",
		"type": "Test type 0",
		"situation": "Test situation 0",
		"timestamp": "1546848000"
	},
	{
		"id": "z69718a1a5z2y5czkwrhr1u37h7h768v05qr3pf1h4r4yrt5a68",
		"name": "Test name 1",
		"country": "Test country 1",
		"type": "Test type 1",
		"situation": "Test situation 1",
		"timestamp": "1741351615"
	},
	{
		"id": "fh974sv586nhyysbhg5nak444968h7hgcgh6yw0usbvcz9b0h69",
		"name": "Test name 2",
		"country": "Test country 2",
		"type": "Test type 2",
		"situation": "Test situation 2",
		"timestamp": "1741351603"
	},
	{
		"id": "347272052385993",
		"name": "Test name 3",
		"country": "Test country 3",
		"type": "Test type 3",
		"situation": "Test situation 3",
		"timestamp": "1741351557"
	}
]  <--- END ARRAY

You should use something like this:

struct NewsFeed: Codable {
    let id, name, country, type: String
    let situation, timestamp: String
}

typealias TheFeed = [NewsFeed]

Or, you could consider how I do this in my own app:

{
	"balance": {
		"current": 342.15,
		"saver": 1813.32
	},
	"date": "202503",
	"data": [
		{
			"date": "20250313",
			"items": [
				{
					"address": "1 High Street",
					"time": "13:52",
					"cost": 6.25
				}
			]
		},
		{
			"date": "20250305",
			"items": [
				{
					"address": "10 The Avenue",
					"time": "13:19",
					"cost": 6.99
				},
				{
					"address": "25 Main Street",
					"time": "07:21",
					"cost": 3.75
				},
				{
					"address": "50 The Street",
					"time": "07:16",
					"cost": 20.8
				}
			]
		}
	]
}

That JSON conforms to these structs:

struct Month: Codable {
	let balance: Balance
	let date: String
	let data: [LineItem]
}

struct LineItem: Codable {
	let date: String
	let items: [Details]
}

struct Details: Codable {
	let address: String?
	let time: String
	let cost: Double
}

struct Balance: Codable {
	let current: Double
	let saver: Double
}

I decode the data into the Month struct because a Month contains a balance of type Balance, a date String and an array of LineItems.

Each LineItem contains a date String and an array of Details.

Each Details contains an address String optional, a time String, and a cost Double.

I don't have a root array; I have a root Month so I have curly braces.

Accepted Answer

The solution was to replace this:

let newsFeed = try decoder.decode(NewsFeed.self, from: data!)

with this:

let newsFeed = try decoder.decode([NewsFeed].self, from: data!)
json array shows in debugger but can't parse (corrected question)
 
 
Q