Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Difficulties parsing JSON Objects #109

Open
giacmarangoni opened this issue May 14, 2017 · 3 comments
Open

Difficulties parsing JSON Objects #109

giacmarangoni opened this issue May 14, 2017 · 3 comments
Labels

Comments

@giacmarangoni
Copy link

giacmarangoni commented May 14, 2017

Hi guys, I really want to thank you for you awesome work, I think Marshal is the fastest and lightweight library to deal with JSON structures.
I'm facing a problem parsing a simple data structures:

"students": {
     "mrngcm":{
         "first_name":"John",
         "last_name":"Doe",
         "courses": {
             "MAT": 28
         }
     }
     ...
}

Here my model class:

import Foundation
import Marshal

class Student: Unmarshaling {
    var id: String
    var firstName: String
    var lastName: String
    var courses: [String:Int]
    
    required init(object: MarshaledObject) throws {
        self.firstName = try object.value(for: "first_name")
        self.lastName = try object.value(for: "last_name")
        self.courses = try object.value(for: "courses")
    }
}
let json: MarshalDictionary = try! JSONSerialization.jsonObject(with: dataFromString, options: []) as! MarshalDictionary
let students: [String: Student] = try! json.value(for: "students")

I don't exactly how to assign key to model id and additionally I'm getting and error while extracting courses dictionary: fatal error: try!' expression unexpectedly raised an error: Type mismatch. Expected type Dictionary<String, Int> for key: courses. Got '__NSArray0

Do you have any suggestion? Thank you so much

@jarsen
Copy link
Member

jarsen commented May 31, 2017

I'm not really sure where Marshal thinks you're getting an array from given your example. But that's what it seems to think.

As to the first part of the question, that's tricky. Marshal isn't designed around this use case. My best suggestion would be to not use any of Marshal's built in helpers for converting collections, and instead do your own for map over the key value pairs of your dictionary. Then, inside the loop, init a a new student object using the dictionary's value, and then set the id to the key.

@jarsen
Copy link
Member

jarsen commented May 31, 2017

in other words, something maybe like

let students = json.map { key, value in
    var student = try Student(object: value)
    student.id = key
    return student
}

@giacmarangoni
Copy link
Author

Thank you for your help. It works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants