evermeer / AlamofireJsonToObjects

An Alamofire extension which converts JSON response data into swift objects using EVReflection
Other
161 stars 28 forks source link

Error parsing array swift 3 #38

Closed sagits closed 7 years ago

sagits commented 7 years ago

Hi @evermeer , i was used to use AlamofireJsonToObjects with swift 2.3 and now im trying to update my apps to swift 3.0. Im have some problems with arrays:

My ws basically has a JsonMessage object which can have an array of objects or a single object (JsonMessageSingle and JsonMessageList). I was able to parse the JsonMessageSingle normally using Generics, but it stuck on this screen when trying to parse the json below (im not sure, but i guessed it cant parse the generic array):

May you help me please? Thanks in advance.

image

{
  "status": "SUCCESS",
  "message": null,
  "data": "2017-01-30 13:56:45",
  "objects": [
    {
      "idPacote": "12",
      "alias": "higienizacao-completa",
      "nome": "Higienização completa",
      "desconto": "10",
      "descricao": "<p>A higieniza&ccedil;&atilde;o completa &eacute; ideal para aquele momento em que voc&ecirc; precisa dar um bom trato no seu ve&iacute;culo. Nesse servi&ccedil;o realizamos a limpeza &nbsp;interna e externa completa, aplicamos os melhores produtos para cada &aacute;rea do seu carro, odorizamos o ambiente interno e realizamos a higieniza&ccedil;&atilde;o no teto, tapetes, estofados e ar-condicionado.</p>",
      "status": "1",
      "vantagens": "<p>Comodidade e seguran&ccedil;a pois vamos&nbsp;at&eacute; o seu ve&iacute;culo;</p>\r\n<p>Ecologicamente correto, pois economiza &aacute;gua e n&atilde;o utiliza produtos qu&iacute;micos;</p>\r\n<p>Extermina &aacute;caros e bact&eacute;rias, evitando ataques al&eacute;rgicos;</p>\r\n<p>Desodoriza por completo o ve&iacute;culo e n&atilde;o somente disfar&ccedil;a com outros produtos;</p>\r\n<p>Conserva a lataria do ve&iacute;culo;</p>\r\n<p>N&atilde;o desgasta o estofado pois n&atilde;o existe a necessidade de esfreg&aacute;-lo;</p>\r\n<p>A limpeza dura duas vezes &nbsp;mais que uma limpeza convencional;</p>\r\n<p>Voc&ecirc; ganha uma economia de tempo e dinheiro;</p>\r\n<p>Carro com aspecto de carro novo e limp&iacute;ssimo;</p>\r\n<p>Higieniza&ccedil;&atilde;o interna e externa completa, incluindo o teto do autom&oacute;vel;</p>\r\n<p>Ar condicionado renovado;</p>\r\n<p>Bancos hidratados e sem risco de ressecamento;</p>\r\n<p>Pneus com brilho, hidrata&ccedil;&atilde;o e prote&ccedil;&atilde;o.</p>",
      "ordem": "2",
      "publico": "<p>Voc&ecirc; tem um evento nos pr&oacute;ximos dias ou est&aacute; precisando impressionar algu&eacute;m? Esse servi&ccedil;o &eacute; ideal para voc&ecirc;. A gente sabe que melhor que assistir ao casamento do seu amigo de inf&acirc;ncia &eacute; fazer as pessoas assistirem o seu carro chegando bonit&atilde;o na festa. Se voc&ecirc; preza pelo cuidado com o seu ve&iacute;culo e quer que ele tenha sempre um aspecto de carro novo, &eacute; a hora ideal para agendar uma higieniza&ccedil;&atilde;o completa.</p>",
      "idAlbum": "4"
    }
  ]
}
class JsonMessageList<T> : JsonMessage<T>, EVGenericsKVC where T:MyModel {
    var objects : [T]?

    required
    init() {
        super.init()
    }

    func getGenericType() -> NSObject {
        return T() as! NSObject
    }

    func setGenericValue(_ value: AnyObject!, forUndefinedKey key: String) {
        switch key {
        case "objects":
            objects = value as! [T]
            break
        default:
            print("---> setValue '\(value)' for key '\(key)' should be handled.")
        }
    }

}

class JsonMessage<T> : EVObject where T:MyModel {

    var message : String?
    var data : String?
    var status : String?

    required
    init() {
        super.init()
    }
}

 func makeRequest(method: HTTPMethod, URL: String, callListener: CallListListener<T>, headers : [String:String]? = nil) {
        callListener.onPreRequestInternal()
        //    print("making request " + getMethod(method) + " to " + URL)

        Alamofire.request(URL, method: method, headers: headers ?? getHeaders())
            .responseJSON { response in
                // do whatever you want here
                switch response.result {
                case .failure(let error):
                    print(error)
                case .success(let responseObject):
                    print(responseObject)
                }
            }

            .responseObject {
                (response: DataResponse<JsonMessageList<T>>) in

                if let result = response.result.value {
                    callListener.afterRequest(response: result)
                } else {
                 //   print("Request failed with error: \(response.response.er)")
                }

        }
evermeer commented 7 years ago

Before going into details... I see this is an older version. A couple of versions ago I change the line where the crash is to:'

        if theValue is Array<Any> {
            return (theValue as AnyObject, valueType, false)
        }

Besides that I also migrated these extensions into EVReflection itself. It's now a subspec. You install it by using:

pod "EVReflection/Alamofire"

Functionally it has not been changed.

One other thing. In the current version you don't need the 'required init' anymore when using generics.

If you want to see generics sample code, then have a look at the files EVReflectionWorkaroundSwiftGenericsTests and NestedGenericsIssue25

I will now have a look at your code to see if I see something strange.

sagits commented 7 years ago

Thanks for answering. Its giving me a "unable to satisfy dependencies" on the pod "EVReflection/Alamofire". Should i include EVReflection too? By now i have:

    pod "EVReflection/Alamofire"
    pod "AlamofireJsonToObjects", '~> 2.4.0' 

EDIT

I understand it now. Alamofire is part of EVReflection (like you said). I had to do a:

pod repo update

To be able to found the pod "EVReflection/Alamofire". I was able to solve my issue updating the pod to the EVReflection subpod.