sergdort / CleanArchitectureRxSwift

Example of Clean Architecture of iOS app using RxSwift
MIT License
3.91k stars 494 forks source link

How to decode json other then using codable? #56

Closed ninjandroid closed 6 years ago

ninjandroid commented 6 years ago

Hello,

in Post entry the part where Encodable do the task to decode json from internet. Is there any efficient and fast way to do this? like say you have nested object in one you gotta have several lines of code just to decode it. Thank you.

celtaheaven commented 6 years ago

You can either use SwiftJSON (https://github.com/SwiftyJSON/SwiftyJSON) or explore the source data using container manipulation (https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types)

ninjandroid commented 6 years ago

Thank you @celtaheaven. If I have a response below with a wrapper in every http request. Using Generics, where T in my case is venue.

Here is my code:

    func getItems(_ path: String) -> Observable<HttpReponse<[T]>> {
        let absolutePath = "\(endPoint)/\(path)"
        return RxAlamofire
            .data(.get, absolutePath)
            .debug()
            .observeOn(scheduler)
            .map({ data -> [T] in
                return try JSON(data: data )
            })

Json:


{
  "meta": {
    "code": 200,
    "requestId": "5ac51d7e6a607143d811cecb"
  },
  "response": {
    "venues": [
      {
        "id": "5642aef9498e51025cf4a7a5",
        "name": "Mr. Purple",
        "location": {
          "address": "180 Orchard St",
          "crossStreet": "btwn Houston & Stanton St",
          "lat": 40.72173744277209,
          "lng": -73.98800687282996,
celtaheaven commented 6 years ago

There are two options I'd use in your case. 1st. its use the SwiftyJSON, unwrap through conditional casting the json["response"]["venuses"] and use it as Data or Dictionary. With that you probably know how you want to use.

2nd. and the option i'd use, is to create ServerResponse struct that is Codable and will be decoded with the JSONDecoder().decode(ServerResponse.self, from: data), using the data retrieved from internet.

The links I've sent fully teaches both ways.

ninjandroid commented 6 years ago

Thank, I opted for the 2nd option :)