ObjectMapper

repository·master·Indexed 27 days ago

https://github.com/tristanhimmelman/objectmapper

A Swift framework for simplifying the conversion between model objects (classes and structs) and JSON. It provides the Mappable, StaticMappable, and ImmutableMappable protocols to handle mutable and immutable models, nested objects via dot notation, and custom transformations using TransformType and TransformOf. The library supports generic objects, mapping contexts for passing additional information, and integration with Realm.

Tokens
4K
Snippets
13
Records
23
Agent score
44%

What's inside ObjectMapper

  1. Convert between JSON and Model objects

    master

    Once a type implements Mappable, you can convert between JSON strings and model instances using either the model's convenience methods or the Mapper class.

    Using Model Convenience Methods:

    • Convert JSON string to object: User(JSONString: JSONString)
    • Convert object to JSON string: user.toJSONString(prettyPrint: true)

    Using the Mapper class:

    • Convert JSON string to object: Mapper<User>().map(JSONString: JSONString)
    • Convert object to JSON string: Mapper().toJSONString(user, prettyPrint: true)
    // Convert JSON String to Model
    let user = Mapper<User>().map(JSONString: JSONString)
    
    // Create JSON String from Model
    let JSONString = Mapper().toJSONString(user, prettyPrint: true)
  2. Install ObjectMapper as a Submodule

    master

    To add ObjectMapper as a git submodule:

    1. Run git submodule add https://github.com/tristanhimmelman/ObjectMapper.git in your project's top-level directory.
    2. Drag ObjectMapper.xcodeproj from the ObjectMapper folder into your app project's file navigator.
    3. In your target configuration, ensure the deployment target of ObjectMapper.framework matches your application target.
    4. In the Build Phases tab, add ObjectMapper.framework to the Target Dependencies group.
    5. Add a new Copy Files Phase, rename it to "Copy Frameworks", set the Destination to "Frameworks", and add ObjectMapper.framework to it.
  3. Install ObjectMapper as a Git Submodule

    master
    1. Run git submodule add https://github.com/Hearst-DD/ObjectMapper.git in your project root.
    2. Drag ObjectMapper.xcodeproj into your app's file navigator in Xcode.
    3. In your target's configuration, under Build Phases, add ObjectMapper.framework to Target Dependencies.
    4. Create a New Copy Files Phase, rename it to "Copy Frameworks", set the Destination to "Frameworks", and add ObjectMapper.framework to the list.
    5. Ensure the deployment target for ObjectMapper.framework matches your main project's deployment target.
    git submodule add https://github.com/Hearst-DD/ObjectMapper.git
  4. Pass custom context during mapping

    master

    You can pass additional information into the mapping process using a MapContext object.

    1. Create a struct or class that conforms to the MapContext protocol.
    2. Pass an instance of this context to the Mapper initializer.
    3. Access the context inside your mapping(map: Map) function by casting map.context to your custom type.
    struct Context: MapContext {
    	var importantMappingInfo = "Extra info"
    }
    
    class User: Mappable {
    	var name: String?
    
    	required init?(map: Map){}
    
    	func mapping(map: Map){
    		if let context = map.context as? Context {
    			// Access extra information here
    		}
    	}
    }
    
    let context = Context()
    let user = Mapper<User>(context: context).map(JSONString)
  5. Subclass Mappable classes

    master

    When subclassing classes that implement the Mappable protocol, you must ensure that the subclass calls the superclass's required initializer and the mapping(map:) function to ensure all properties from the hierarchy are correctly mapped.

    class Base: Mappable {
        var base: String?
        
        required init?(map: Map) {}
    
        func mapping(map: Map) {
            base <- map["base"]
        }
    }
    
    class Subclass: Base {
        var sub: String?
    
        required init?(map: Map) {
            super.init(map: map)
        }
    
        override func mapping(map: Map) {
            super.mapping(map: map)
            sub <- map["sub"]
        }
    }
  6. Map nested JSON objects using dot notation

    master

    ObjectMapper supports dot notation to access nested keys in a JSON structure.

    • Nested Objects: Use map["parent.child"] to access parent -> child.
    • Arrays: Use index notation like map["array.0.key"] to access specific elements in a nested array.
    • Disable Nesting: If your key contains a literal dot, use nested: false: map["app.identifier", nested: false].
    • Custom Delimiters: If your keys contain dots but you want to use a different separator for nesting, use the delimiter parameter: map["com.myapp.info->com.myapp.name", delimiter: "->"].
  7. Convert between JSON and Mappable objects

    master

    Once a type implements Mappable, you can convert between JSON strings and model objects using either the object's convenience methods or the Mapper class.

    Using object methods:

    • JSON String to Object: User(JSONString: JSONString)
    • Object to JSON String: user.toJSONString(prettyPrint: true)

    Using the Mapper class:

    • JSON String to Object: Mapper<User>().map(JSONString: JSONString)
    • Object to JSON String: Mapper().toJSONString(user, prettyPrint: true)
  8. Inherit Mappable classes

    master

    Classes implementing Mappable can be inherited. When overriding the mapping(map: Map) function in a subclass, ensure you call super.mapping(map: map) to include the parent class's properties.

    class Base: Mappable {
        var base: String?
        required init?(map: Map) {}
        func mapping(map: Map) {
            base <- map["base"]
        }
    }
    
    class Subclass: Base {
        var sub: String?
        required init?(map: Map) {
            super.init(map: map)
        }
        override func mapping(map: Map) {
            super.mapping(map: map)
            sub <- map["sub"]
        }
    }