5

I have a JSON response like:

      {
        total_count: 155,
        size: 75,
        authors: [{ name: "test1"
                    id: 1

                 },
                 {name: "test2"
                    id: 2
                 }]
      }

I created my object model and use objectMapper for mapping/parsing this json.

import Foundation
import SwiftyJSON
import ObjectMapper

class Author: Mappable {
    var id: Int!
    var name: String!

    required init?(map: Map) {

    }

    func mapping(map: Map) {
        self.id <- map["id"]
        self.name <- map["name"]
    }

    static func fromJSONArray(_ json: JSON) -> [Author] {
        var authorArray: [Author] = []
        if json.count > 0 {
            for item in json["authors"]{
                print(item)
                authorArray.append(Mapper<Author>().map(JSONObject: item)!)
            }
        }
        return authorArray
    }

With print(item) I can see the objects but, I can't make append work. It is giving "Unexpectedly found nil while unwrapping an Optional value" error.

2 Answers 2

1

Your JSON is not valid.

You can check your JSON validity using JSONLint for exemple.

For more safety in your code, avoid usage of !.

Replace

authorArray.append(Mapper<Author>().map(JSONObject: item)!)

by

if let author = (Mapper<Author>().map(JSONObject: item) {
    authorArray.append(author) 
} else {
    print("Unable to create Object from \(item)")
}
Sign up to request clarification or add additional context in comments.

4 Comments

JSON is valid I checked using JSONLint. I edited the code as you suggested. I am getting Unable to create .... error. But I can see the item. Is there something wrong with the mapping code?
Can you add the print of item ? In string mode ?
Unable to create Object from ("1", { "id" : 1, "name" : "test1"}
This is not a Valid JSON.
0

You have invalid JSON ,
As per your json authors is dictionary but author dictionary there is no key

As well as inside array there is dictionary but no brackets and comma

Your correct JSON is

authors: [ 
       {
        name: "",
        id: 0
       }

     ]

And then your code looks ok to me

   if json.count > 0 {
        for item in json["authors"]{
            print(item)
            authorArray.append(Mapper<Author>().map(JSONObject: item)!)
        }
    }

EDIT

Try this out

      if json.count > 0 {
            for item in json["authors"]{
                print(item)
                 do {
                   let objectData = try JSONSerialization.data(withJSONObject: item, options: .prettyPrinted)
                  let string = String(data: objectData, encoding: .utf8)
                authorArray.append(Mapper<Author>().map(JSONObject: string)!)

                  } catch {
                     print(error)
                   }
            }
        }

Comments

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.