0

This is my API response...

{
    "organizations": [
        {
            "id": 12345,
            "name": “products1",
            "parentId": null,
            "plantId": 28768,
            "type": 1
        },
        {
            "id": 76532,
            "name": “products2",
            "parentId": 4270947,
            "plantId": null,
            "type": 2
        }
    ]
}

Now since I have some issues with connectivity and so cannot call the API, get the response and parse, I have hard-coded the above response in my code like so..

var jsonObject = [String : [[String : Any?]]]()


jsonObject = [
    "organizations":[

    ["id": 12345, “name”: “products1”, “parentId”:”null”,"plantID”:28768,”type”:1],
    ["id": 76532, “name”: “products1”, “parentId”:”null”,"plantID”:28768,”type”:1]

    ]

]

And I parse this data and insert it into database like so...

let organizationLists = Organization()

guard let jsonArray = jsonObject as? [String : [[String : Any?]]] else { return }

for (_,value) in jsonArray {

    for object in value {

        organizationLists.id = object["id"] as? Int
        organizationLists.Name = object["name"] as? String
        organizationLists.parentID = object["parentID"] as? Int
        organizationLists.plantID = object["plantID"] as? Int
        organizationLists.loggedInUserId = object["type"] as? Int
        let isInserted = sharedInstance.saveOrganization_Lists(organizationLists)
    }            
}

Now with the above code, I'm able to properly insert the data also into the database. But I feel that there might be a better way to directly parse based on the value rather than using a for loop inside a for loop like above..or maybe a totally different and better method altogether...

EDIT 1: Class for Codable

class OrganizationLists: Codable{
    var id: Int?
    var name: String?
    var parentID: Int?
    var plantID: Int?
    var type: Int?

    //Initialize as usual
    init(id: Int, name: String, parentID: Int, plantID: Int, type: Int) {
        self.id = id
        self.name = name
        self.parentID = parentID
        self.plantID = plantID
        self.type = type
    }
}
8
  • 1
    Yes my dude. I'm about to change your life forever. Allow me to share a code snippet of great gloriousness that will make your life infinitely easier. #codable/decodable Commented Apr 7, 2020 at 13:54
  • 1
    Where does jsonObject come from? It's obviously already deserialized. Commented Apr 7, 2020 at 14:44
  • @xTwisteDx I'm sorry your answer won't solve that even if jsonObject was Data. Commented Apr 7, 2020 at 14:48
  • @vadian can you explain? I'm always up to learning something. Commented Apr 7, 2020 at 14:52
  • @vadian would you maybe mind suggesting an answer... Commented Apr 7, 2020 at 14:53

1 Answer 1

2

Usually you receive the data from an API response as raw Data representing a JSON string.

let jsonString = """
{
    "organizations": [
        {
            "id": 12345,
            "name": "products1",
            "parentId": null,
            "plantId": 28768,
            "type": 1
        },
        {
            "id": 76532,
            "name": "products2",
            "parentId": 4270947,
            "plantId": null,
            "type": 2
        }
    ]
}
"""

let data = Data(jsonString.utf8)

Don't use a class unless you really need a class and declare only those properties as optional which can be nil. If you are not going to modify the values declare the properties even as constants (let).

Further you need an umbrella struct for the root object

struct Root : Decodable {
    let organizations : [Organization]
}

struct Organization : Decodable {
    let id: Int
    let name: String
    let parentID: Int?
    let plantID: Int?
    let type: Int
}

Now decode the data

do {
    let result = try JSONDecoder().decode(Root.self, from: data)
    print(result)
} catch {
    print(error)
}
Sign up to request clarification or add additional context in comments.

6 Comments

Just a note, if you use a Struct, you cannot pass objects by reference. If you know you'll be passing by ref, you'll need a Class, otherwise a Struct will suffice. I'd nearly call this sniping, but whatever. I'll be a good sport.
Please note unless you really need a class.
Pardon for the late reply @vadian. Thanks a lot for the answer. Now I get this in the result : Root(organizations: [eSMAT.Organization1(id: 12345, name: “products1”, parentID: nil, plantID: Optional(28768),type: 1)…..]). But I'm confused as to how I can parse and get each of the individual elements from this response....
It's unclear what type your database accepts. If Organization is compatible then you can insert the array result.organizations directly. Otherwise make the database type conform to Codable.
Thanks a lot @vadian. I tried result.organizations and it is working fine. Just one more doubt..In case my json response did not have organizations, but instead was a simple one like [ { "id": 12345, "name": “products1” … } ] then how I could have used Codable/Decodable..?
|

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.