sergdort / CleanArchitectureRxSwift

Example of Clean Architecture of iOS app using RxSwift

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to decode json other then using codable?

ninjandroid opened this issue · comments

commented

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.

commented

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,

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.

commented

Thank, I opted for the 2nd option :)