JSON Array for Swift object 3

Asked

Viewed 330 times

1

There is someone help me and guide me, I am studying iOS development so I put a library "Alamofire" with cocoapods to consume JSON so far so good, only my JSON returns like this:

{
  "results":[
     {
        "id":7,
        "descricao":"Acupuntura",
        "campoOrderBy":"descricao"
     }
]
}

Is there a library that I can put these guys into entities, attributes, variables in a simple way, have any articles, sites that can see that ? Any hints where to start studying ?

2 answers

0

You can use the Ocmapper:

Example of JSON:

{
   "firstName"   : "FirstName",
   "lastName"    : "LastName",
   "age"         : 26,
   "dateOfBirth" : "01/01/2013",
   "address"     : { 
                        "city" : "San Diego", 
                        "country" : "US"  
                   },
   "posts"       : [
                         {
                             "title" : "Post 1 title",
                             "datePosted : "04/15/2013",
                         },
                         {
                             "title" : "Post 2 title",
                             "datePosted : "04/12/2013",
                         }
                   ]
}

An object with JSON data:

@objc public class User: NSObject {

    var firstName: String?
    var lastName: String?
    var age: NSNumber?
    var dateOfBirth: NSDate?
    var address: Address?
    var posts: [Post]? // Repare que como é um array no JSON, será necessário criar outro Objeto chamado Post para receber os dados de dentro do array
}

Swift usage:

let user = ObjectMapper.sharedInstance().objectFromSource(dict, toInstanceOfClass:User.self) as User

Objective-C use:

User *user = [[ObjectMapper sharedInstance] objectFromSource:dictionary toInstanceOfClass:User.class];

Integration into the Alembic so that it is already the parser of the request, have an example in the link above.

0

Hello, you can use the protocol Codable Swift. Currently Swift, in version 5, has the Encodable and the Decodable. The Encodable serves to encode an object for json and Decodable does reverse work. By extending Codable You’re saying that the structure or class can be either encoded or decoded. In most cases we do both processes, but it is possible that there is a case in which we just want to encode or just decode. In such cases it is possible to extend only Encodable or just Decodable.

For your case just create the structures extending from Codable as follows:

struct ObjetoInterno: Codable {
  var id: String
  var descricao: String
  var campoOrderBy: String
}

struct ResultadoDaChamada: Codable {
  var results: [ObjetoInterno]
}

And to convert json to the structure ResultadoDaChamada, use as follows after obtaining the result of your call:

let stringJson = """
{
    "results":
        [
            {
            "id":7,
            "descricao": "Acupuntura",
            "campoOrderBy":"descricao"
            }
        ]
}
"""

if let dadosJson = stringJson.data(using: .utf8){
    do {
        let resultado = try JSONDecoder().decode(ResultadoDaChamada.self, from: dadosJson)
        print(resultado)
    } catch let error {
        print(error)
    }
}

A good source of information about this is Apple’s documentation: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types

Browser other questions tagged

You are not signed in. Login or sign up in order to post.