Codable: Expected to decode Array<Any> but found a dictionary instead - swift

I'm new to Codable and been playing around it today.
My current JSON model look like this:
{
"status": 200,
"code": 200,
"message": {
"1dHZga0QV5ctO6yhHUhy": {
"id": "23",
"university_location": "Washington_DC",
"docID": "1dHZga0QV5ctO6yhHUhy"
},
"0dbCMP7TrTEnpRbEleps": {
"id": "22",
"university_location": "Timber Trails, Nevada",
"docID": "0dbCMP7TrTEnpRbEleps"
}
}
}
However, Trying to decode this response with:
struct USA: Codable
{
//String, URL, Bool and Date conform to Codable.
var status: Int
var code: Int
// Message Data
var message: Array<String>
}
Gives out:
Expected to decode Array but found a dictionary instead.
Updating the message to Dictionary<String,String produces:
typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "message", intValue: nil), _JSONKey(stringValue: "1dHZga0QV5ctO6yhHUhy", intValue: nil)], debugDescription: "Expected to decode String but found a dictionary instead.", underlyingError: nil))

message key is a dictionary not an array
struct Root: Codable {
let status, code: Int
let message: [String: Message]
}
struct Message: Codable {
let id, universityLocation, docID: String
}
do {
let dec = JSONDecoder()
dec.keyDecodingStrategy = .convertFromSnakeCase
let res = try dec.decode(Root.self, from: data)
}
catch{
print(error)
}

Related

Need to map the json to model in Swift

I have a Json response that i get from a API, the json looks like something like this
{
"data": [
{
"_id": "63d9d2d57c0cfe791b2b19f6",
"step": {
"_id": "step1",
"status": "STARTED",
"children": [
{
"_id": "step2",
"status": "NOT_STARTED",
"children": [
{
"_id": "step3",
"status": "NOT_STARTED",
"children": [
{
"_id": "step3",
"status": "NOT_STARTED"
}
]
}
]
}
]
},
"status": "IN_PROGRESS",
"createdBy": "2700930039"
}
]
}
The json can have multiple levels of children objects inside each other. I need to map this json response to Models in swift
Here are the Models for the Json that i created
struct NestedJsonModel:Decodable {
var data:[LotData]
}
struct LotData:Decodable {
var _id: String
var step: StepDetails
var status: String
var createdBy: String
}
struct StepDetails:Decodable {
var _id: String
var status: String
var children: [ChildSteps]
}
struct ChildSteps:Decodable {
var _id: String
var status: String
var children: [StepDetails] //because children contains the same model as Step Details
}
Here is the decoder code
let jsonData = data.data(using: .utf8)!
do {
let decoder = JSONDecoder()
let tableData = try decoder.decode(NestedJsonModel.self, from: jsonData)
result = tableData.data
print("****************")
print(result!)
print("****************")
}
catch {
print (error)
}
But i keep getting this error
keyNotFound(CodingKeys(stringValue: "children", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "step", intValue: nil), CodingKeys(stringValue: "children", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "children", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"children\", intValue: nil) (\"children\").", underlyingError: nil))
Notice that the innermost layer of your JSON does not have a "children" key, but your ChildSteps struct does have a non-optional children property that needs to be assigned some value.
To fix this, you just need to make children have an optional type.
Also note that since StepDetails and ChildSteps have the same properties, you can merge them too.
struct NestedJsonModel:Decodable {
var data:[LotData]
}
struct LotData:Decodable {
var _id: String
var step: StepDetails
var status: String
var createdBy: String
}
struct StepDetails:Decodable {
var _id: String
var status: String
var children: [StepDetails]?
}
If you don't need to differentiate between "having an empty children array" and "not having the children key at all", then you can make the children property non-optional, and initialise it with an empty array when the key is not found.
This can be conveniently done without handwriting your own custom decoding logic by using a property wrapper as shown in this answer:
#propertyWrapper
struct DefaultEmptyArray<T:Decodable>: Decodable {
var wrappedValue: [T] = []
init() {}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
wrappedValue = try container.decode([T].self)
}
}
extension KeyedDecodingContainer {
func decode<T:Decodable>(_ type: DefaultEmptyArray<T>.Type,
forKey key: Key) throws -> DefaultEmptyArray<T> {
try decodeIfPresent(type, forKey: key) ?? .init()
}
}
// in StepDetails
#DefaultEmptyArray var children: [StepDetails]?

SwiftUI - No value associated with key CodingKeys

I am currently trying to write a universal Request object in my SwiftUI application that aligns with an API I am building. I have written out something simple with the JSON payload that I have as an example and am running into an issue with the decoding of the object. Below is the Request object.
let json = """
{
"object": "bottle",
"has_more": false,
"data": [
{
"id": "5ffa81e7-1d91-43b5-83cc-9ee1ab634c7b",
"name": "14 Hands Hot to Trot White Blend",
"price": "$8.99",
"image": "https://cdn11.bigcommerce.com/s-7a906/images/stencil/1000x1000/products/8186/10996/14-Hands-Hot-to-Trot-White-Blend__56901.1488985626.jpg?c=2",
"sku": "088586004490",
"size": "750ML",
"origination": "USA, Washington",
"varietal": "White Wine",
"information": "14 Hands Hot to Trot White Blend",
"proof": 121.5,
"brand_id": "1",
"rating": 1,
"review_count": 5
}
]
}
"""
struct Request: Decodable {
let object: String
let has_more: Bool
let data: [RequestData]
}
struct Bottle: Decodable {
let id: String
let name: String
let price: String
let image: String
let sku: String
let size: String
let origination: String
let varietal: String
let information: String
let proof: Float
let brand_id: String
let rating: Int
let review_count: Int
}
enum ObjectType: String, Decodable {
case bottle
}
enum BottleData: Decodable {
case bottle(Bottle)
}
struct RequestData: Decodable {
let hasMore: String
let object: ObjectType
let innerObject: BottleData
enum CodingKeys: String, CodingKey {
case hasMore
case object
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.object = try container.decode(ObjectType.self, forKey: .object)
self.hasMore = try container.decode(String.self, forKey: .hasMore)
switch object {
case .bottle:
self.innerObject = .bottle(
try Bottle(from: decoder)
)
}
}
}
let decoder = JSONDecoder()
let requestData = try decoder.decode(Request.self, from: json.data(using: .utf8)!)
for data in requestData.data {
switch data.innerObject {
case .bottle(let bottle):
print(bottle.name)
}
}
I am recieving the following error when trying to test this object.
DecodingError
▿ keyNotFound : 2 elements
- .0 : CodingKeys(stringValue: "object", intValue: nil)
▿ .1 : Context
▿ codingPath : 2 elements
- 0 : CodingKeys(stringValue: "data", intValue: nil)
▿ 1 : _JSONKey(stringValue: "Index 0", intValue: 0)
- stringValue : "Index 0"
▿ intValue : Optional<Int>
- some : 0
- debugDescription : "No value associated with key CodingKeys(stringValue: \"object\", intValue: nil) (\"object\")."
- underlyingError : nil
Given that I only have one object at the moment, I'm a little confused as to why this is not working as I expect (without any errors). Can anybody spot what I may be doing wrong here?
Please read the error carefully.
The CodingPath components indicate the exact location of the error. It's
CodingKeys(stringValue: "object", intValue: nil)
CodingKeys(stringValue: "data", intValue: nil)
_JSONKey(stringValue: "Index 0", intValue: 0)
CodingKeys(stringValue: "object", intValue: nil).
which – translated to a key path – is
object.data[0].object
The actual error message
"No value associated with key CodingKeys(stringValue: "object", intValue: nil) ("object")."
states that there is no key object in the RequestData object which it is true.
I guess it's just a typo. Replace
let data: [RequestData]
with
let data: [Bottle]
and remove RequestData and the associated structs. They are pointless.
Edit:
You can do something like this, but as the JSON contains only one type the solution only decodes this particular JSON
let json = """
{
"object": "bottle",
"has_more": false,
"data": [
{
"id": "5ffa81e7-1d91-43b5-83cc-9ee1ab634c7b",
"name": "14 Hands Hot to Trot White Blend",
"price": "$8.99",
"image": "https://cdn11.bigcommerce.com/s-7a906/images/stencil/1000x1000/products/8186/10996/14-Hands-Hot-to-Trot-White-Blend__56901.1488985626.jpg?c=2",
"sku": "088586004490",
"size": "750ML",
"origination": "USA, Washington",
"varietal": "White Wine",
"information": "14 Hands Hot to Trot White Blend",
"proof": 121.5,
"brand_id": "1",
"rating": 1,
"review_count": 5
}
]
}
"""
enum RequestData {
case bottle([Bottle])
}
enum ObjectType: String, Decodable {
case bottle
}
struct Request: Decodable {
let object: ObjectType
let hasMore: Bool
let data: RequestData
enum CodingKeys: String, CodingKey { case hasMore = "has_more", object, data}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.object = try container.decode(ObjectType.self, forKey: .object)
self.hasMore = try container.decode(Bool.self, forKey: .hasMore)
switch object {
case .bottle:
let bottleData = try container.decode([Bottle].self, forKey: .data)
data = RequestData.bottle(bottleData)
}
}
}
struct Bottle: Decodable {
let id: String
let name: String
let price: String
let image: String
let sku: String
let size: String
let origination: String
let varietal: String
let information: String
let proof: Float
let brand_id: String
let rating: Int
let review_count: Int
}
let decoder = JSONDecoder()
let requestData = try decoder.decode(Request.self, from: Data(json .utf8))
print(requestData)

How do I make a struct with nested json?

I have a JSON response from my api that returns this:
[
{
"id": 1,
"chapter": 5,
"amount": 28,
"texts": [
{
"lyric": "lorem ipsum",
"number": 1
},
{
"lyric": "lorem foo bar",
"number": 2
}
],
"book": 1
}
]
I tried
struct Chapter: Decodable, Identifiable {
var id: Int
var chapter: Int
var amount: Int
struct Lyrics: Codable {
var lyricText: String
var lyricNumber: Int
}
enum Codingkeys: String, CodingKey {
case lyricText = "lyric"
case lyricNumber = "number"
}
}
But I get the following error upon making the call
dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))
My API call looks like this:
...
#Published var chapters = [Chapter]()
func fetchBookDetails() {
if let url = URL(string: url) {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error == nil {
if let safeData = data {
do {
let response = try JSONDecoder().decode([Chapter].self, from: safeData)
DispatchQueue.main.async {
self.chapters = response
}
} catch {
print(error)
}
}
}
}
task.resume()
}
}
The struct looks fine I guess, but the api call is complaining - any idea what it could be? Or is it the struct that is done incorrectly
texts is a sub structure (an array of properties), so you need to define a second container for it, for example
struct Text: Codable {
let lyric: String
let number: Int
}
Then you can update Chapter to reference the sub structure something like...
struct Chapter: Decodable {
let id: Int
let chapter: Int
let amount: Int
let book: Int
let texts: [Text]
}
And finally, load it...
let chapters = try JSONDecoder().decode([Chapter].self, from: jsonData)
But what about the error message?
dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))
Oh, right, but the error message is telling there is something wrong with what you've downloaded. I like to, in these cases, convert the data to String and print it if possible, that way, you know what is been returned to you.
For example:
let actualText = String(data: safeData, encoding: .utf8)
The print this and see what you're actually getting
The Playground test code
import UIKit
let jsonText = """
[
{
"id": 1,
"chapter": 5,
"amount": 28,
"texts": [
{
"lyric": "lorem ipsum",
"number": 1
},
{
"lyric": "lorem foo bar",
"number": 2
},
],
"book": 1
}
]
"""
struct Text: Codable {
let lyric: String
let number: Int
}
struct Chapter: Decodable {
let id: Int
let chapter: Int
let amount: Int
let book: Int
let texts: [Text]
}
let jsonData = jsonText.data(using: .utf8)!
do {
let chapters = try JSONDecoder().decode([Chapter].self, from: jsonData)
} catch let error {
error
}

Swift - Constructing a base Decodable struct with Generics

So, I am trying to build a model that will be responsible for URLRequests and parsing Decodables. The response that is coming from the server is in the same form at the highest scope including keys status, page_count and results.
results values are changing respecting to the request, page_count is optional and status is just a String indicating whether the request was successful or not.
I tried to implement Generics to method itself and base Decodable struct named APIResponse and below is an example of just one endpoint, named extList. The code compiles, however in the runtime it throws
Thread 7: Fatal error: 'try!' expression unexpectedly raised an error:
Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "results",
intValue: nil), Swift.DecodingError.Context(codingPath: [],
debugDescription: "No value associated with key
CodingKeys(stringValue: \"results\", intValue: nil) (\"results\").",
underlyingError: nil))
at the line of json = try! JSONDecoder().decode(APIResponse<T>.self, from: data)
class NetworkManager {
typealias completion<T: Decodable> = (Result<APIResponse<T>, Error>)->()
class func make<T: Decodable>(of type: T.Type,
request: API,
completion: #escaping completion<T>){
let session = URLSession.shared
var req = URLRequest(url: request.url)
req.httpMethod = request.method
req.httpBody = request.body
session.dataTask(with: req) { (data, response, error) in
if let error = error {
completion(.failure(error))
return
}
var json: APIResponse<T>
if let data = data,
let response = response as? HTTPURLResponse?,
response?.statusCode == 200 {
switch request {
case .extList:
json = try! JSONDecoder().decode(APIResponse<T>.self, from: data)
default:
return
}
completion(.success(json))
}
}.resume()
}
}
Here is the base struct
struct APIResponse<T: Decodable>: Decodable {
var status: String
var page_count: Int?
var results: T
}
Here is the response that should fill the results key in the APIResponse for this endpoint.
struct UserResponse: Decodable {
var name: String
var extens: Int
}
I am making my request as NetworkManager.make(of: [UserResponse].self, request: .extList) { (result) in ; return } and it works when I discard the Response generic type in the APIResponse with the Array<UserResponse> directly.
As requested, sample json I am trying to decode
{
"status": "ok-ext_list",
"page_count": 1,
"results": [
{
"name": "some name",
"extens": 249
},
{
"name": "some other name",
"extens": 245
}
]
}
Any ideas to fix this?
MINIMAL REPRODUCIBLE EXAMPLE
So the below code is working and I absolutely do not know why.
JSON's
import Foundation
var extListJSON : Data {
return try! JSONSerialization.data(withJSONObject: [
"status": "ok_ext-list",
"page_count": 1,
"results": [
[
"name": "some name",
"extens": 256
],
[
"name": "some other name",
"extens": 262
]
]
], options: .fragmentsAllowed)
}
var extListString: Data {
return """
{
"status": "ok-ext_list",
"page_count": 1,
"results": [
{
"name": "some name",
"extens": 249
},
{
"name": "some other name",
"extens": 245
}
]
}
""".data(using: .utf8)!
}
Manager and Service
enum Service {
case extList
}
class NetworkManager {
typealias completion<T: Decodable> = (APIResponse<T>) -> ()
class func make<T: Decodable>(of type: T.Type, request: Service, completion: completion<T>) {
let data = extListString
let json: APIResponse<T>
switch request {
case .extList:
json = try! JSONDecoder().decode(APIResponse<T>.self, from: data)
}
completion(json)
}
}
Decodables
struct APIResponse<T: Decodable>: Decodable {
var status: String
var page_count: Int?
var results: T
}
struct UserResponse: Decodable {
var name: String
var extens: Int
}
Finally method call
NetworkManager.make(of: [UserResponse].self, request: .extList) { (result) in
dump(result)
}
Again, I have no clue why this is working. I just removed the networking part and it started to work. Just a reminder that my original code is working as well if I just use seperate Decodable for each request -without using Generic struct-. Generic make(:_) is working fine as well.

Swift 4 decoding json using Codable

Can someone tell me what I'm doing wrong? I've looked at all the questions on here like from here How to decode a nested JSON struct with Swift Decodable protocol? and I've found one that seems exactly what I need Swift 4 Codable decoding json.
{
"success": true,
"message": "got the locations!",
"data": {
"LocationList": [
{
"LocID": 1,
"LocName": "Downtown"
},
{
"LocID": 2,
"LocName": "Uptown"
},
{
"LocID": 3,
"LocName": "Midtown"
}
]
}
}
struct Location: Codable {
var data: [LocationList]
}
struct LocationList: Codable {
var LocID: Int!
var LocName: String!
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "/getlocationlist")
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
guard error == nil else {
print(error!)
return
}
guard let data = data else {
print("Data is empty")
return
}
do {
let locList = try JSONDecoder().decode(Location.self, from: data)
print(locList)
} catch let error {
print(error)
}
}
task.resume()
}
The error I am getting is:
typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath:
[], debugDescription: "Expected to decode Array but found a
dictionary instead.", underlyingError: nil))
Check the outlined structure of your JSON text:
{
"success": true,
"message": "got the locations!",
"data": {
...
}
}
The value for "data" is a JSON object {...}, it is not an array.
And the structure of the object:
{
"LocationList": [
...
]
}
The object has a single entry "LocationList": [...] and its value is an array [...].
You may need one more struct:
struct Location: Codable {
var data: LocationData
}
struct LocationData: Codable {
var LocationList: [LocationItem]
}
struct LocationItem: Codable {
var LocID: Int!
var LocName: String!
}
For testing...
var jsonText = """
{
"success": true,
"message": "got the locations!",
"data": {
"LocationList": [
{
"LocID": 1,
"LocName": "Downtown"
},
{
"LocID": 2,
"LocName": "Uptown"
},
{
"LocID": 3,
"LocName": "Midtown"
}
]
}
}
"""
let data = jsonText.data(using: .utf8)!
do {
let locList = try JSONDecoder().decode(Location.self, from: data)
print(locList)
} catch let error {
print(error)
}
After searching lots of thing internet, I certainly figured out this is the sweetest way to print well formatted json from any object.
let jsonString = object.toJSONString(prettyPrint: true)
print(jsonString as AnyObject)
Apple documentation about JSONEncoder ->
struct GroceryProduct: Codable {
var name: String
var points: Int
var description: String?
}
let pear = GroceryProduct(name: "Pear", points: 250, description: "A ripe pear.")
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try encoder.encode(pear)
print(String(data: data, encoding: .utf8)!)
/* Prints:
{
"name" : "Pear",
"points" : 250,
"description" : "A ripe pear."
}
*/