Giter Site home page Giter Site logo

objectmapper's Introduction

tristanhimmelman

objectmapper's People

Contributors

anton-plebanovich avatar bdbergeron avatar bilal-wego avatar busta117 avatar cezheng avatar dershowitz011 avatar devxoul avatar emrcftci avatar fegabe avatar gcharita avatar haritowa avatar heyzooi avatar hiroraba avatar ikesyo avatar ken0nek avatar kenji21 avatar kishikawakatsumi avatar lacklock avatar mazyod avatar pizthewiz avatar r-plus avatar rkawajiri avatar romanpodymov avatar ruben-samsonyan avatar selvam4274 avatar thii avatar traylewin avatar tristanhimmelman avatar vitkuzmenko avatar xai3 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

objectmapper's Issues

Create a new release/tag with podspec file

Hi,

I'm using cocopods 0.36 beta 1 to manage dependencies in my Swift project, this project has ObjectMapper as dependency and I missed a release with podspec file, can you create a new release based on master branch which already has the podspec file commited?

Thanks!

Can't map array from root node of json

Hi. I have following json:

[
{
"id": 12,
"name": "Alex",
"age": 18
},
{
"id": 13,
"name": "John",
"age": 23
}
]

I parsed this json by "Jackson" java library and use this json in multiple app. And now i want parse this in swift in iOS app. I make each object of this array as Mappable, But i don't know how i can map this as Array where "ProfileInfo" is my Mappable object. I wrote this code:

Mapper<[ProfileInfo]>().map(string: json);

But get error that say [ProfileInfo] is not Mappable.
Please help ! Thank's.

put the transform dir in 1 swift file

Hi,

first of all, great gob with this ObjectMapper!. Just a small request, it is not required for Swift to have a file for each class separately. So perhaps you could merge the whole Transformation directory into one swift file. The swift files contain mostly 1 class with 10 lines of code. I think its better to have one class with maybe 100 lines with all that stuff inhere, and it can reside win the core dir with other files...

iOS 7 Cocoapods support

When installing ObjectMapper as a pod the xcode project would complain and give the error message that embedded frameworks are only supported on iOS8.

Could we fix this please as the adoption rate of iOS8 is only at 69% and I assume many apps will still need iOS 7 support?

Cannot apply Mappable Protocol to NSManagedObject Subclass

I'm seeing a very obscure build error with objects inheriting from NSManaged object, the code below is extracted form a sample project based on the MasterDetail template. ObjectMapper is installed via 0.36.0.beta.2 Cocoapods with the _Event and Event classes generated with mogenerator 1.28 --v2 --swift. It makes no difference whether the protocol is applied to the derived Human readable class or the Machine Readable class inherited form NSManagedObject.
This builds OK:
import Foundation
import ObjectMapper
class Lump: Mappable {
var timeStamp : NSDate?
required init() {}
func mapping(map : Map) {
timeStamp <= (map["timeStamp"],DateTransform())
}
}

This does not:

import ObjectMapper
@objc(Event)
class Event: _Event, Mappable {
func mapping(map : Map) {
timeStamp <= (map["timeStamp"],DateTransform())
}
}

The error message is
CompileSwiftSources normal x86_64 com.apple.xcode.tools.swift.compiler
.. snip ..
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

Can´t use ObjectMapper in WatchKit Extension: Linking against dylib not safe for use in application extensions

I´m using carthage to add ObjectMapper to my WatchKit Extension.

...a warning occurs:
Linking against dylib not safe for use in application extensions

bildschirmfoto 2015-03-23 um 23 03 12 18 02

This is also described here: https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html

To configure an app extension target to use an embedded framework, set the target’s “Require Only App-Extension-Safe API” build setting to Yes. If you don’t, Xcode reminds you to do so by displaying the warning “linking against dylib not safe for use in application extensions”.

I´ve done this, the warning still occurs. Is this a problem on my side or does ObjectMapper need to do something? I´ve also included Alamofire and SwiftyJSON the same way, they link without warnings.

Can't map json string into my class!

I can't map the json string into my object.
I have two classes: Categoria (https://github.com/tmnd1991/poiuytrewq/blob/master/proprioluimix/Model/Categoria.swift)
and Registrazione (https://github.com/tmnd1991/poiuytrewq/blob/master/proprioluimix/Model/Registrazione.swift).
Then i try to run the following:
let reg = Registrazione(n: "pane",fn: "cane")
let cat = Categoria(_name: "Pippo", _registrazioni: [reg])
let catJson = Mapper().toJSONString(cat,prettyPrint: true)
println(catJson)
let catBack = Mapper().map(catJson)
println(catBack)
the first "println" prints the correct json string, but the second prints nil.
Am I making any mistake in the use of the library? Or it's an issue?

Add an external parameter name to Map.map(JSON: AnyObject?)

Both of the API's below can accept String as valid input. The only difference in the calls when passing in a String is whether you included the parameter name "string:". Inadvertently calling the second API when you intend to call the first is easy to do and cause for hardship. I suggest adding an external parameter name to the second API to avoid this problem.

/** 
        * Map a JSON string to an object that conforms to Mappable
    */
    public func map(string JSONString: String) -> N? 
/**
    * Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is
    */
    public func map(JSON: AnyObject?, var toObject object: N) -> N 

Suggestion:

    public func map(object JSON: AnyObject?, var toObject object: N) -> N

Doubles not mapped correctly

When using a mapping class with a Double? property the mapped dictionary for the property shows as an NSDecimalNumber but the value is null.

The JSON looks like this:
{"PlanId":2,"Progress":[{"TaskId":103,"Percentage":0.0},{"TaskId":108,"Percentage":1762.0}]}

loss order when deserializing json string

[{name:"a", path:"/root/a"}, {name:"b", path:"/root/a/b"}]

when deserializing the json, got an array
array[0] {name:"b", path:"/root/a/b"}
array[1] {name:"a", path:"/root/a"}

can ObjectMapper keep the order when deserializing

array[0] {name:"a", path:"/root/a"}
array[1] {name:"b", path:"/root/a/b"}

Build failed on iPhone 5

Hi,

I want to use ObjectMapper in my project but i have a build failed when i compile it on iPhone 5 (but it compiles on iPhone 5S and higher).

Here are the issue logs:
Swift compiler error
Use of undeclared type 'Mapper'
Swift compiler error
Use of undeclared type 'MapperProtocol'

Regards,
Dohko

How to handle collections?

Hi Tristan,
If your JSON returns a collection, how do you go about this? Since your mapper requires a string.
For instance like so:

[
    {
        "name": "My pretty beacon NO#1",
        "UUID": "3C074D4B-FC8C-4CA2-82A9-6E9367BBC875",
        "major": 541,
        "minor": 123
    },
    {
        "name": "My pretty beacon NO#2",
        "UUID": "3C074D4B-FC8C-4CA2-82A9-6E9367BBC876",
        "major": 54321,
        "minor": 13
    }
]

Or would you first convert the string to JSON, loop through the collection and per item create a string that is mapped to your ObjectMapper?

Best,
Sidney

Cannot convert an object contains generic member

Can this module convert object such as bellow?

let response = Mapper().map(string: result, toType: Response<Status>.self)

class Response<T:MapperProtocol>: MapperProtocol {
    var result: T?

    required init() {
    }

    fund map(mapper: Mapper) {
        result <= mapper[“result”]
    }   
}

class Status: MapperProtocol {
    var code: Int?

    required init() {
    }

    fund map(mapper: Mapper) {
        status <= mapper[“code”]
    }
}

Actually I use result(string) look like this

"{\"result\":{\”code\":0}}”

So, I expect to get a response contains 0. But the result is value Builtin.Word 4328602064.

I cannot solve on my own.
If you have any tip, please let me know.
Thank you

Guidance needed: how to pass a Mappable to a function that can map to it as a generic?

I've tried a bunch of things which compile but don't result in what I expect, in mysterious ways. This is more of a general Swift question but should be a common use case of this lib, so I'm asking it here.

My use case: I have an API client method that takes the "model" type to de-serialize to as a parameter. I need to instantiate this Mappable model type inside the function, to return the de-serialized object.

Anyone have a way to get this working? It seems so simple...

More complex data structures / Nested collections

Hi Tristan,
Been using you library for some time now, and i really like it. I did however run into a slight pickle.
What if the incoming data has nested collections? Like so:

{
    "contacts": [
        {
            "id": "62e8686b",
            "name": "Person A"
        },
        {
            "id": "9e7c4271",
            "name": "Person B"
        },
        {
            "id": "d5c3fb7f1aae",
            "name": "Person C"
        }
    ]
}

My data mapper class now looks like this - but it seems that this is an incorrect approach:

class AddressBookMap: MapperProtocol {

    var contacts: Array<ContactMap>?

    required init(){

    }

    func map(mapper: Mapper) {

        self.contacts <= mapper["contact"]
    }
}

Hopefully you can help me in the correct direction,

Cheers,
Sidney

Thread and async problems...

Do you have any problems with threads or async tasks during the mapping process? I get a request and map the json via

let json = JSON(responseObject)
var array: Array<AF_Poi> = Array()
for (index: String, subJson: JSON) in json {
let data = Mapper<AF_Poi>().map(subJson.dictionaryObject!)
array.append(data)
}

During the mapping process, the ui on the main thread is blocked. Do you have any ideas what to do about that?

Mapping [String]

Hi there,

I don't think this is a bug, just my ignorance.

I have a var in my class which I would like to map to via mapping(map:), so I'm trying to do something along the lines of

// Where domains is of type [String]
self.domains <- map["domains"]

I tried writing a TransformType, StringArrayTransform, which I'm fairly certain isn't the right solution, to turn [AnyObject] into [String], and still no luck.

Any thoughts?

Other than that, everything is working great, so thanks a lot for the library!

How to map from Alamofire JSON response AnyObject?

As the title says. How do I map from Alamofire JSON response AnyObject?

Alamofire.request(.GET, URL + "Timetable").responseJSON { (_, _, JSON, _) in
let timeTable = Mapper().map(JSON, toType: Timetable.self)
}
JSON is AnyObject? but the map function does not accept that. How can I proceed?

Support for mapTo and mapFrom

There are times when interfacing with an API that it expects different JSON in the request from what is returned in the response. For example, if I have a user class, and i want to update the user on the backend, the request I send will be as follows:

{user: {"id" : 1,
"name" : "myname"}}

However the response will return:

{"id" : 1, "name" : "myname"}

The response does not have the "user" parameter in the JSON.

It would be good if the mappable protocol has two methods: mapFromJSON and mapToJSON

that allows us to define different mappings based on whether its being mapped from or to the object.

Please let me know if there's another way to do this in the current implementation.

Problem in mapping numberic strings

Hi all.
I have this json:
{
"id": "2",
"name": "alex",
"city": "1"
},
{
"id": "3",
"name": "Lindy",
"city": "1"
},....

The type of "id" and "city" in my Mappable object is Int. But after mapping, id and city is 0. When i changed the type of this field to String, the result is OK and mapping is successful.

This is my bean:

import UiKit

class Region: Mappable {

var id : Int = 0
var name : String = ""
var city : Int = 0

init(){}    

required init?(_ map : Map){
    mapping(map)
}

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

}

How i solve this issue?

Xcode 6.3 and ObjectMapper 0.9

Hey has anyone seen this? I recently updated my xcode to 6.3. So I updated my cartfile as well to the new github "Hearst-DD/ObjectMapper" ~> 0.9 But everytime I run carthage update I get this:

*** Building scheme "ObjectMapper-iOS" in ObjectMapper.xcodeproj
** BUILD FAILED **
The following build commands failed:
CompileSwift normal x86_64 .../Carthage/Checkouts/ObjectMapper/ObjectMapper/Core/Mapper.swift
CompileSwiftSources normal x86_64 com.apple.xcode.tools.swift.compiler
(2 failures)

Issue with NSManagedObject class conforming to Mappable

Hi,

I'm trying to map directly JSON to a class model inheriting NSManagedObject. I created an extension that conform to Mappable and implement mapping.

At compile time, I got a Swift compiler error, usr/bin/swiftc failed to exit code 1.

It might be due to the init() method of the Mappable protocol. When reading the Mapper.swift class I found the following:

   /**
* Maps a JSON dictionary to an existing object that conforms to Mappable.
* Usefull for those pesky objects that have crappy designated initializers like NSManagedObject
*/
public func map(JSON: [String : AnyObject], var toObject object: N) -> N {
    let map = Map(mappingType: .fromJSON, JSONDictionary: JSON)
    object.mapping(map)
    return object
}

which would be the function to use in order to set properties of the entity once created.

Could you post an example of an NSManagedObject class conforming to Mappable?

Thanks

CoreData relationships support

Hi, thanks for taking the time to make a great library and save time to others. Good job.

I''ve modified the lib a bit in order to support creating instances from CoreData entities (also avoid duplicates using identification attributes, similar to how RestKit handles it).
I had to create a custom transform that its main method looks like this:

override func transformFromJSON(value: AnyObject?) -> NSSet? {
    var set = NSMutableSet()
    if let array = value as? [AnyObject] {
        for object in array {
            if let dict = object as? [String : AnyObject] {
                set.addObject(self.mapper.map(dict, toType: EntityType.self))
            }
        }
    }
    return set
}

I ended up with the right set built up, but then I get a crash (bad_access) on this operator overload:

public func <=<T, N>(inout left: T, right: (Mapper, MapperTransform<T, N>)) {
    if right.0.mappingType == MappingType.fromJSON {
        var value: T? = right.1.transformFromJSON(right.0.currentValue)
       //println("FromJSON \(value)");
       FromJSON<T>().baseType(&left, object: value)
   } else {
       var value: N? = right.1.transformToJSON(left)
       //println("\(left) toJSON \(value)")
       ToJSON().optionalBaseType(value, key: right.0.currentKey!, dictionary: &right.0.JSONDictionary)
   }
}

This line in particular FromJSON().baseType(&left, object: value).

So even I'm pretty new to swift, I think this is related to the inout param not admitting obj-c interoperability. If that's the case, do you see any possible workaround in order to set a NSSet via a custom transform? If that's not what's happening, do you have any ideas what I might be doing wrong?

Thanks a lot again.

Mariano

Parse json object with unknown keys

Hi,
Suppose you have json like this:

{
"someUUID": {"name": "Joe", "age": 20},
"otherUUID": {"name": "Tom", "age": 25},
...
}

The UUID keys are not known at compile time, so cannot be hardcoded. How can this be parsed and mapped with ObjectMapper?

Add PodSpec to Cocoapods

Now that Cocoapods supports swift (0.36 preview), it would be really cool to have a podspec there.

parse integer response always nil

It's not same as #62

json:
{"id": 70, "title":"xxxx"}

mapper:

class Tigo: Mapper {
var id: Int64? // alway nil
//var id: Int? // id is 70

var title: String?

func mapping(map: Map) {
  id <= map["id"]
  title <= map["title"]
}
}

Help Wanted: Mapping Arrays of Mappables?

So I have a JSON response that is an array. I want to map each index in the array to a Challenge object. I thought it would be possible to use ObjectMapper in the following manner.

let challenges:[Challenge] = Mapper<Array<Challenge>>().map(responseString)

Unfortunately I get and error Type 'Array<Challenge>' does not conform to protocol 'Mappable',

Should I just write an extension for Array<T: Mappable> which implements the Mappable protocol?

Cannot invoke '<=' with custom transformer

Hi, I've been having an issue with custom transformers. Take the following model object:

class Example: MapperProtocol {
    var date: NSDate?

    required init(){}

    func map(mapper: Mapper) {
        date <= (mapper["birthday"], DateTransform<NSDate, Int>())
    }
}

If DateTransform is defined in a file within my project, I receive the following error: "Cannot invoke '<=' with an argument list of type '(@lvalue NSDate?, (@lvalue Mapper, DateTransform<NSDate, Int>))'"

If DateTransform is defined in the ObjectMapper project, I do not receive this error and the mapping works as expected.

Note: The DateTransform defined in my project was exactly the same as the built-in DateTransform and I deleted the built-in one to avoid conflicts.

DateTransform crashing

With the following on Xcode 6.1 and SWIFT I'm getting a crash on the following function in Transforms/DateTransform.swift:

override public func transformToJSON(value: ObjectType?) -> JSONType? {
if let date = value as? NSDate {
return (Double(date.timeIntervalSince1970) as JSONType) // crashes here <------
}
return nil
}

The class triggering the error is:

class Test: Mappable {
var dob: NSDate?
required init() {}
func map(mapper: Mapper)
{
dob <= (mapper["dob"], DateTransform<NSDate, Int>())
}
}

It is invoked as:

var t = Test()
t.dob = NSDate()
let js = Mapper().toJSONString(t, prettyPrint: true)
println(js)

Mapping nested values

Mantle has a nice feature for JSON structured like this:

 "distance" : {
     "text" : "102 ft",
     "value" : 31
  }

Rather than creating a transformer or another type to handle things like this you can do distance.value

Would you consider/accept patches for functionality like this for ObjectMapper? Or do you have any better ideas?

I think something like:

 object.distance <= mapper["distance.value"] 

would be nice.

[RFC] Rename MapperProtocol to something

The name MapperProtocol is long a little bit, and also Swift protocols are mainly named with suffix like Type (e.g. SequenceType) or able (e.g. Equatable, Hashable, and so on).

How do you think about renaming it to something like MapperType or Mappable?

A little help with nested objects needed

I need a little guidance with mapping nested objects. I managed to use ObjectMapper with built in types perfect. But how do I map nested custom objects?

Given something like this:

class A {
    let b: B
    let c: [C]
}

As I said I managed to map B and C alone. But how do I map it from inside A? Do I need to write a custom transform? Or do I need to make B and C conform to some protocol? I am guessing it is quite simple but I just can't get my head around it.

Calling Mapper().toJSON(object) modifies the underlying object properties

I'm facing a very weird issue where calling Mapper().toJSON(object) modifies object's properties.
I noticed this because I also use this object with realm, and modifying an object outside a transaction will crash the app.

To reproduce, you can create a new single view project in XCode, add ObjectMapper as a pod and Realm as a framework manually. Then create a User model that is a RLMObject and that conforms to MapperProtocol. Create a user, insert it in the realm, then try to convert it to JSON outside of the write transaction.

User.swift

import Foundation
import Realm
import ObjectMapper

class User: RLMObject, MapperProtocol {
    dynamic var name: String?

    override required init!() {
        super.init()
    }

    func map(mapper: Mapper) {
        name <= mapper["name"]
    }
}

ViewController.swift

import UIKit
import Realm
import ObjectMapper

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        var user = User()
        user.name = "bla"

        let realm = RLMRealm.defaultRealm()
        realm.beginWriteTransaction()
        realm.addObject(user)
        realm.commitWriteTransaction()

        let dictionary = Mapper().toJSON(user) // Crashes on this line
    }
}

To make things easier, here's the full project: https://s3.amazonaws.com/uploads.hipchat.com/13599/245679/bPBl5yiijSuxJBX/TestObjectMapping.zip

Stack before crash

Make sure you have an All exceptions breakpoint set up.

image

Crash message

2015-01-20 21:47:06.061 TestObjectMapping[14330:1161838] *** Terminating app due to uncaught exception 'RLMException', reason: 'Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.'
*** First throw call stack:
(
    0   CoreFoundation                      0x00000001106d7b75 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000011225fbb7 objc_exception_throw + 45
    2   TestObjectMapping                   0x000000010fd53a85 _ZL11RLMSetValueP9RLMObjectmP11objc_object + 1285
    3   TestObjectMapping                   0x000000010fd5583b ___ZL13RLMMakeSetterIU8__strongP11objc_objectS2_EPFvvEmb_block_invoke_2 + 19
    4   TestObjectMapping                   0x000000010fd4ee2e _TFC17TestObjectMapping4User3mapfS0_FC12ObjectMapper6MapperT_ + 1374
    5   TestObjectMapping                   0x000000010fd4f1fe _TTWC17TestObjectMapping4User12ObjectMapper14MapperProtocolFS2_3mapUS2___fRQPS2_FCS1_6MapperT_ + 78
    6   ObjectMapper                        0x0000000110061d31 _TFC12ObjectMapper6Mapper6toJSONfS0_US_14MapperProtocol__FQ_GVSs10DictionarySSPSs9AnyObject__ + 561
    7   TestObjectMapping                   0x000000010fd4a07f _TFC17TestObjectMapping14ViewController11viewDidLoadfS0_FT_T_ + 2703
    8   TestObjectMapping                   0x000000010fd4a172 _TToFC17TestObjectMapping14ViewController11viewDidLoadfS0_FT_T_ + 34
    9   UIKit                               0x000000011108bf10 -[UIViewController loadViewIfRequired] + 738
    10  UIKit                               0x000000011108c10e -[UIViewController view] + 27
    11  UIKit                               0x0000000110faaeb9 -[UIWindow addRootViewControllerViewIfPossible] + 58
    12  UIKit                               0x0000000110fab251 -[UIWindow _setHidden:forced:] + 247
    13  UIKit                               0x0000000110fb793c -[UIWindow makeKeyAndVisible] + 42
    14  UIKit                               0x0000000110f61c01 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 2732
    15  UIKit                               0x0000000110f649a3 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1349
    16  UIKit                               0x0000000110f63875 -[UIApplication workspaceDidEndTransaction:] + 179
    17  FrontBoardServices                  0x000000011751a253 __31-[FBSSerialQueue performAsync:]_block_invoke + 16
    18  CoreFoundation                      0x000000011060c9bc __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    19  CoreFoundation                      0x0000000110602705 __CFRunLoopDoBlocks + 341
    20  CoreFoundation                      0x0000000110601ec3 __CFRunLoopRun + 851
    21  CoreFoundation                      0x0000000110601906 CFRunLoopRunSpecific + 470
    22  UIKit                               0x0000000110f632e2 -[UIApplication _run] + 413
    23  UIKit                               0x0000000110f660e0 UIApplicationMain + 1282
    24  TestObjectMapping                   0x000000010fd4fe1e top_level_code + 78
    25  TestObjectMapping                   0x000000010fd4fe5a main + 42
    26  libdyld.dylib                       0x00000001132cc145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

I tried to explore the operator overloading jungle but couldn't find where ObjectMapper modifies the object. I'm really surprised that it's even a thing, serializing should not do that.

Any idea of what's going on?

Removal of toType affects subclassing

Hi, in the process of updating my code to accommodate the changes introduced by this commit, (which removed toType), I noticed that my mapping no longer behaves as expected. Specifically, I get the following compiler error when trying to override the map method in a subclass that uses generics: Method does not override any method from its superclass.

Here is a simplified example of my use case:

class Base: Mappable {
    required init() {}

    func map<N>(mapper: Mapper<N>) {

    }
}

class Sub<T>: Base {
    required init() {
        super.init()
    }

    override func map<N>(mapper: Mapper<N>) { //Compiler error

    }
}

Removing override gets rid of the error, but the method on the subclass is never called. Adding a generic to the base class (making it Base<T>) seems to fix the problem, but defeats the purpose of my base class (it allows me to pass around instances of the subclass without knowing their generic type).

Do you know of a possible workaround for this? Please let me know if additional info is needed.

Thanks,
Noah

Incorrect compiler behavior for overloaded parsing functions(Xcode Version 6.1.1 (6A2008a))

In Mapper.swift class following function recursively calls itself when [String : AnyObject] object is passed to it which leads to stack overflow.

public func map(JSON: AnyObject?, var toObject object: N) -> N {
if let JSON: [String : AnyObject] = JSON as? [String : AnyObject] {
return map(JSON, toObject: object)
}
return object
}

Removing it results in correct behavior because the function variant with dictionary param is called instead.

Map [N] to JSON array

By looking at the source code, I can't find a way to map [N] -> [[String: AnyObject]]. Is there a way to do it with the current state of the code (without iterating directly)? If not, I might PR something.

Non-optional mapping

I want to create an object from JSON, but if any of the properties aren't set successfully, e.g. the corresponding JSON value is missing or malformed, I want to return a nil object. The upside is that I can then assume that any object created from JSON has all of the required properties, and thus I don't need to use optionals. Is there a way to do this?

Can't map a generic array

Attempting to map to a generic array of a generic superclass whose type is specified explicitly by a subclass always yields nil.

See #66 for an example and failing test case.

custom subtypes cannot be implicitly unwrapped optionals

Trying to make a custom subtype an implicitly unwrapped optional causes a runtime crash on line 31 of FromJson.swift. This doesn't seem to affect types such as strings and ints. For example if the User object from the docs were to be declared var friend: User! this should reproduce the crash.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.