ava ava - 1 month ago 11
iOS Question

JSON Parsing (swift)

I am trying parse this JSON

["Items": <__NSSingleObjectArrayI 0x61000001ec20>(

{

AccountBalance = 0;

AlphabetType = 3;

Description = "\U0631\U06cc\U0648";

FullCode = "P_21_JIM_456_IR_25";

IRNumber = 25;

LeftNumber = 21;

RightNumber = 456;

}

)

, "ErrorCode": 0, "ErrorMessage": , "Result": 1]


how can access to items parameter in this case? I'm trying create structure for Items but I have an this error : Cannot convert value of type '(key: String, value: AnyObject)' to expected argument type '[String : AnyObject]'
what is solution for access Items parameter ?

there is my Items structure and parsing JSON code :

struct PalletItems {

let accountBalance : Int
let alphabetType : Int
let description : String
let fullCode : String
let irNumber : Int
let leftNumber : Int
let rightNumber : Int

init? (accountBalance: Int, alphabetType: Int, description : String, fullCode: String, irNumber: Int, leftNumber: Int, rightNumber: Int ) {


self.accountBalance = accountBalance
self.alphabetType = alphabetType
self.description = description
self.fullCode = fullCode
self.irNumber = irNumber
self.leftNumber = leftNumber
self.rightNumber = rightNumber

}



func palletListFromJSONData(_ data : Data) -> PaletListResult {



do{
let jsonresult : [String : AnyObject]
= try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:AnyObject]
print("json : \(jsonresult)")
let success = jsonresult["Items"] as? PalletItems
print("items is : \(success)")

for paletJson in jsonresult {
if let palet = getBalanceOfWalletFromJsonObject(paletJson) {

finalResult.append(palet)
}
}


let palet = getBalanceOfWalletFromJsonObject(jsonresult)

finalResult.append(palet!)

return .success(finalResult)

}

catch let error as NSError{
print("that is parsing json error : \(error)")

return .failure(error)
}
}


func getBalanceOfWalletFromJsonObject(_ json: [String: AnyObject]) -> ListOfPlates?{

guard let
errorCode = json["ErrorCode"] as? Int,
let errorMessage = json["ErrorMessage"] as? String,
let result = json["Result"] as? Int,
let item = json["Items"] as? PalletItems

else {
return nil
}
let obj = ListOfPlates(errorCode: errorCode, errorMessage: errorMessage, result: result, items: item)

return obj
}

Answer

The problem is you're trying to access it as key value pair but you're getting it as an array. So the json should be of [[String:Any]] Now this json should be parsed as json.first! which gives you [String:Any]. Now you can get the value of any key.

Comments