0

I'm almost new to swift and I'm facing a runtime error which says:

typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary but found an array instead.", underlyingError: nil))

I have an Array of data that I need to send to the API.

The code below shows the model that the API will accept

Json

 {
  "items": [
    {
      "Number": 1,
      "ID": 9827
    }

  ]
}

my struct:

    struct Itemm : Codable {
    var unitNo:Int? 
    var personId:Int?

    enum iItem : Int ,CodingKey{
        case unitNo , personId
    }

}
struct welcome : Codable {
    var items : [Itemm?]
}
typealias welcomeList = [welcome]

the code below shows the way I'm creating my array and trying to send it to Server

    var items = [Itemm]()
            for indexPath in self.selectedCells {
                let data = self.data![indexPath.section]
                let contact = data.contacts[indexPath.row]
                let newItem = Itemm(unitNo: data.unitNo, personId: contact?.id)
                items.append(newItem)
            }
    //      let welcome = welcome(items: items)
            print(items)
            let welcomee = welcome(items: items)
            print(welcomee)
            do{

       //I found this part on stackoverflow
            let dict = try JSONDecoder().decode([String: Int].self, from: JSONEncoder().encode(items))
                print("===============")
                print(dict)
                print("********************")
                Presenter.sendSmsForAllTheMembers(AptId: aptId, data: dict)
            }
            catch let error
            {
                print(error)
            }

I'm using Alamofire and Moya library. does anybody know how should I send my request to API?

func sendSmsForAllTheMembers(AptId:String , data:[String:Any])
{
    ApiGenerator.request(targetApi: ApartemanService.sendSms(aptId: AptId, data: data), responseModel: Nil.self, success: { (response) in
        if response.response.statusCode == 200 {
            self.view?.SendingSmsSuccess()
        }else {
            do{

                var errorMessage = try response.response.mapString()
                errorMessage = errorMessage.replacingOccurrences(of: "\"", with: "",
                                                                 options: NSString.CompareOptions.literal, range:nil)
                print("errorMessage =============")
                print(errorMessage)
                self.view?.SendingSmsFailed(errorMessage: errorMessage)

            }catch let error{
                print(error)
                self.view?.SendingSmsFailed(errorMessage: "خطا در ارتباط با سرور")
            }

        }

    }) { (error) in
        self.view?.SendingSmsFailed(errorMessage: "خطا در ارتباط با سرور")
    }
    }
1
  • I'm not super familiar with Moya but, just as a glance, it seems like your var items = [Itemm]() is an array, and you are using the JSONEncoder to encode this and send it as a dictionary. You may want to try converting the items array to a dictionary (see here) and determine if that makes a difference. Note that that may lead to parsing issues on the server side, but it'd be interesting to know if that resolves Xcode's error. Commented Sep 20, 2018 at 1:46

1 Answer 1

2

The encoding is fine, but the re-decoding fails.

The error message is pretty clear. You have to decode an array.

try JSONDecoder().decode([[String: Int]].self...

But as the API expects a dictionary you might create the dictionary directly

var items = [[String:Int]]()
for indexPath in self.selectedCells {
    let data = self.data![indexPath.section]
    let contact = data.contacts[indexPath.row]
    items.append(["Number" : data.unitNo, "ID" : contact!.id])
}
let welcome = ["items" : items]
print(welcome)
Presenter.sendSmsForAllTheMembers(AptId: aptId, data: welcome)
Sign up to request clarification or add additional context in comments.

11 Comments

I get an error when I try this!! Cannot convert value of type '[[String : Int]]' to expected argument type '[String : Any]'
There are some inconsistencies in the code. The iItem enum has no effect and the keys in the JSON don't match the struct members.
the first part of the code that shows the json is one of the problems that I don't know that my struct is correct or not!
I was just answering the question to resolve the type mismatch error. To resolve subsequent errors – as I said already – there are too many inconsistencies and missing information in the code. For example why do you encode and decode right back? Why do you encode items instead of more likely welcomee? What is sendSmsForAllTheMembers?
I updated the answer with a suggestion but I have no idea if it works.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.