Dealing with Array Problem in iOS Swift 3 when converting Object to JSON

public class LessonAssignment {

    private var title : String?
    private var category : String?
    private var week : Int?
    private var day : Int?


    //Title
    public func getTitle() -> String {
        return title!
    }

    public func setTitle(title : String) {
        self.title = title
    }

    //Category
    public func getCategory() -> String {
        return category!
    }

    public func setCategory(category : String) {
        self.category = category
    }

    //Week
    public func getWeek() -> Int {
        return week!
    }

    public func setWeek(week : Int) {
        self.week = week
    }

    //Day
    public func getDay() -> Int {
        return day!
    }

    public func setDay(day : Int) {
        self.day = day
    }

/**
    Returns an array of models based on given dictionary.

    Sample usage:
    let lessonAssignment_list = LessonAssignment.modelsFromDictionaryArray(someDictionaryArrayFromJSON)

    - parameter array:  NSArray from JSON dictionary.

    - returns: Array of LessonAssignment Instances.
*/
    public class func modelsFromDictionaryArray(array:NSArray) -> [LessonAssignment]
    {
        var models = [LessonAssignment]()
        for item in array {
            models.append(LessonAssignment(dictionary: item as! NSDictionary)!)
        }
        return models
    }

/**
    Constructs the object based on the given dictionary.

    Sample usage:
    let lessonAssignment = LessonAssignment(someDictionaryFromJSON)

    - parameter dictionary:  NSDictionary from JSON.

    - returns: LessonAssignment Instance.
*/
     init() { }

    required public init?(dictionary: NSDictionary) {

        title = dictionary["title"] as? String
        category = dictionary["category"] as? String
        week = dictionary["week"] as? Int
        day = dictionary["day"] as? Int
    }


/**
    Returns the dictionary representation for the current instance.

    - returns: NSDictionary.
*/
    public func dictionaryRepresentation() -> NSDictionary {

        let dictionary = NSMutableDictionary()

        dictionary.setValue(self.title, forKey: "title")
        dictionary.setValue(self.category, forKey: "category")
        dictionary.setValue(self.week, forKey: "week")
        dictionary.setValue(self.day, forKey: "day")

        return dictionary
    }

    func toDictionary() -> [String : Any] {
        var dictionary = [String:Any]()
        let otherSelf = Mirror(reflecting: self)

        for child in otherSelf.children {
            if let key = child.label {
                dictionary[key] = child.value
            }
        }
        return dictionary
    }
}



public class LessonPlan {
    private var name : String?
    private var weeks : Int?
    private var days : Int?
    private var hours : Int?
    private var lessonAssignment = [LessonAssignment]()
    private var lessonNote = [LessonNote]()


    //Name
    public func getName() -> String {
        if name == nil {
            return ""
        } else {
            return name!
        }
    }

    public func setName(name : String) {
        self.name = name
    }

    //Weeks
    public func getWeeks() -> Int {
        if weeks == 0 {
            return 0
        } else {
            return weeks!
        }
    }

    public func setWeeks(weeks : Int) {
        self.weeks = weeks
    }

    //Days
    public func getDays() -> Int {
        if days == 0 {
            return 0
        } else {
            return days!
        }
    }

    public func setDays(days : Int) {
        self.days = days
    }

    //Hours
    public func getHours() -> Int {
        if days == 0 {
            return 0
        } else {
            return hours!
        }
    }

    public func setHours(hours : Int) {
        self.hours = hours
    }

    //LessonAssignment
    public func getLessonAssignment() -> [LessonAssignment] {
        return lessonAssignment
    }

    public func setLessonAssignment(lessonAssignment : [LessonAssignment]) {
        self.lessonAssignment = lessonAssignment
    }

    //LessonNote
    public func getLessonNote() -> [LessonNote] {
        return lessonNote
    }

    public func setLessonNote(lessonNote : [LessonNote]) {
        self.lessonNote = lessonNote
    }


/**
    Returns an array of models based on given dictionary.

    Sample usage:
    let lessonPlan_list = LessonPlan.modelsFromDictionaryArray(someDictionaryArrayFromJSON)

    - parameter array:  NSArray from JSON dictionary.

    - returns: Array of LessonPlan Instances.
*/
    public class func modelsFromDictionaryArray(array:NSArray) -> [LessonPlan]
    {
        var models:[LessonPlan] = []
        for item in array
        {
            models.append(LessonPlan(dictionary: item as! NSDictionary)!)
        }
        return models
    }

/**
    Constructs the object based on the given dictionary.

    Sample usage:
    let lessonPlan = LessonPlan(someDictionaryFromJSON)

    - parameter dictionary:  NSDictionary from JSON.

    - returns: LessonPlan Instance.
*/
     init() { }

    required public init?(dictionary: NSDictionary) {

        name = dictionary["name"] as? String
        weeks = dictionary["weeks"] as? Int
        days = dictionary["days"] as? Int
        hours = dictionary["hours"] as? Int

        lessonAssignment = LessonAssignment.modelsFromDictionaryArray(array:dictionary["lessonAssignment"] as! NSArray)

        lessonNote = LessonNote.modelsFromDictionaryArray(array: dictionary["lessonNote"] as! NSArray)
    }


/**
    Returns the dictionary representation for the current instance.

    - returns: NSDictionary.
*/
    public func dictionaryRepresentation() -> NSDictionary {
        let dictionary = NSMutableDictionary()
        dictionary.setValue(self.name, forKey: "name")
        dictionary.setValue(self.weeks, forKey: "weeks")
        dictionary.setValue(self.days, forKey: "days")
        dictionary.setValue(self.hours, forKey: "hours")
        return dictionary
    }

    func toDictionary() -> [String : Any] {
        var dictionary = [String:Any]()
        let otherSelf = Mirror(reflecting: self)

        for child in otherSelf.children {
            print("Child = \(child)")
            print("Child Label = \(String(describing: child.label))")
            print("Child Value = \(child.value)")

            if let key = child.label {
                 dictionary[key] = child.value
            }
        }
        return dictionary
    }
}

public class ServerRequest {

private var lessonPlan : LessonPlan?

init() {
}

//LessonPlan
public func getLessonPlan() -> LessonPlan {
    return lessonPlan!
}

public func setLessonPlan(lessonPlan : LessonPlan) {
    self.lessonPlan = lessonPlan
}

func toDictionary() -> [String : Any] {
    var dictionary = [String:Any]()
    let otherSelf = Mirror(reflecting: self)

    for child in otherSelf.children {
        if let key = child.label {
            dictionary[key] = lessonPlan?.toDictionary()
        }
    }
    return dictionary
}

}

Current Response = ["lessonPlan": ["name": "test", "days": 2, "weeks": 1, "hours": 1, "lessonAssignment": [HSP.LessonAssignment, HSP.LessonAssignment], "lessonNote": []]]

Expected Response = ["lessonPlan": ["name": "test", "days": 2, "weeks": 1, "hours": 1, "lessonAssignment": [["title" : "some value 1", "category" : "some value", "week" : 1, "day" : 2]], "lessonNote": []]]

Instead of the LessinAssignment Object I would like to add the actual values which is array. Any clue how to resolve this. I know i have to add some more logic inside the toDictionary method and based on the key "lessonAssignment" I have to get each array and add the value in the key as final Array.

Answer №1

Here's a snippet based on my comment:

assignments.map({
  (value: HSP.LessonAssignment) -> NSDictionary in
  return value.toDictionary()
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to merge strings and JMESPath queries in order to construct a webhook payload?

I'm currently exploring the use of Cloud Custodian webhooks to generate tagged events in Datadog using the Datadog API. The code snippet below is almost functional, however, the tag for account_id is not being created in Datadog. When examining the b ...

JSON data does not display correctly after applying SerializeJSON function

When attempting to serialize the following data into JSON and checking the output, I am encountering a problem as demonstrated below: Line #13 : <cfset convertjson = SerializeJSON([ { ...

An error is thrown by the Jersey Client API when attempting to send a PUT request with

Encountering an issue while attempting to PUT a JSONObject as inputData, which looks like this: { "key1": "value1", "key2": "value2" } Here is the code snippet: WebResource webResource = client .resource(url); response = webResource.type(Medi ...

Guide on converting a JSON object to GSON in Java

Here is the API response returned in JSON format: {"id":1,"bps_id":"C199","summary":{"as_of_date":"2017-06-20","bp_earned":0,"bp_balance":"199400","bp_redeemed":"600"},"bps_message":{"eng":"mobile testing message","chi":"mobile testing message chi"},"bps_ ...

N8N: Deleting JSON Key from Output

Is it possible to remove the json key in my output file? I am unsure of the best approach to achieve this. I would like to return an array of data with all values, not just one value. If you want more information, here is a link to my N8N post: Manipulate ...

Converting Nested JSON into a Pandas Data Frame

How can we efficiently convert the following JSON dataset snapshot into a Pandas Data Frame? Importing the file directly results in a format that is not easily manageable. Presently, I am utilizing json_normalize to separate location and sensor into diff ...

Guide on integrating a custom language parser and syntax validation into Monaco editor

I am in need of guidance on how to define a custom language in the Monaco editor. Despite my efforts, I have been unable to locate a reliable source for this documentation. My goal is to create a language with syntax similar to JavaScript, enabling users ...

To trigger the action of any button in Ionic/Angular, I need to double-click

I am encountering an issue with an app that I developed using the Ionic framework. While the app works perfectly on Android devices, I am facing a peculiar situation on iOS. Every time I click a button in the Simulator or on an actual iOS device, I have t ...

Receiving a 405 Method Not Allowed error when accessing a WCF REST service using jQuery

I've developed a WCF rest service that needs to be accessed through jQuery. The service is currently running on my local machine. However, it seems to only accept GET requests, as any other method results in a 405 (Method Not Allowed) error. I'm ...

Eliminate an item from a JavaScript array

I am trying to remove a specific element from a JavaScript array. The element I need to remove is the one with the value of 'NT'. In my HTML input, I have: <input type="text" id="caseType" size="50"/> To populate it, I use: var c ...

Exploring JSON data manipulation with jq

Looking to extract data from a JSON file Data input: { "pools":[ { "id":"403add1f-25d9-4a24-99ff-12c5559fecfa", "members":[ { "id":"2b8e1155-aae0- ...

Arranging and refining elements in a list of documents that contain lists

My Desired Output: I am looking to display the expected results of processing documents using the mongoDB command. (Note: Some documents may not contain arrays.) Documents for Processing { "_id": ObjectId("60ddc26b03edfb7a6b424f10"), "mem ...

Retrieve data from a JSON gist by parsing it as a query string

I have a JavaScript-based application with three key files: index.html app.js input.json The app.js file references input.json multiple times to populate content in div elements within index.html. My goal is to enhance the functionality so that when acc ...

How to troubleshoot Python errors (+mod_wsgi) using the Chrome Network panel

As a newcomer to Python, I am facing an issue with viewing error messages. The problem arises when a javascript function is making a call as follows: $.getJSON('test.py', {data: 'somedata'}, function(return){alert(return.echo)}) In th ...

App crash on IOS only occurs when running on a physical device, but not when running on the simulator

Following a successful build in Xcode, my app runs smoothly on the simulator and my iPhone. However, when I distribute it for testing, it crashes whenever test users attempt to perform a search. If I hardcode the URL elements, everything works perfectly b ...

Encountering a 500 error when sending JSON requests to a Ruby on Rails server application

I developed a Ruby on Rails server application hosted on Heroku that is designed to accept HTTP POST requests containing JSON strings and then add the JSON objects to the database. The application consists of two database models: thanksgivings and requests ...

How can Tweepy be utilized to extract the integer count and incorporate it?

Hope all is well with everyone here. My apologies if this question has been addressed previously, but I am currently working on the following task. cursor = tweepy.Cursor( api.search_tweets, q = '"Hello"', lang = 'en&ap ...

Converting JSON data (using jQuery) into key-value pairs

My JSON object includes various properties that I need to send to a C# web service using jQuery.ajax(). Here's an example of how it looks: var obj = {}; obj.LanguageCode = 1031; obj.Gender = { 'Geschlecht': 'Mann' }; obj.City = { ...

Tips on effectively utilizing the generic class type parameter class

One interesting aspect of my work involves a genetic class parameter public static <T> T parse(String json, Class<T> clazz) { T result = null; result = mapper.readValue(json, clazz); return result; } Imagine there is a JSON object l ...

Verify whether the JSON file has an empty string within a bash script

Greetings, the structure of my Json file is as demonstrated below: { "num_sensor" : 1, "J2" : {"B" : "sensor0", "A" : "sensor1", "D" : "sensor2" , "C" : " ...