• Stars
    star
    1,174
  • Rank 38,222 (Top 0.8 %)
  • Language
    Swift
  • License
    Apache License 2.0
  • Created over 8 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A JSON deserialization library for Swift

Mapper

Mapper is a simple Swift library to convert JSON to strongly typed objects. One advantage to Mapper over some other libraries is you can have immutable properties.

Installation

use_frameworks!

pod "ModelMapper"
github "lyft/mapper"

Usage

Simple example:

import Mapper
// Conform to the Mappable protocol
struct User: Mappable {
  let id: String
  let photoURL: URL?

  // Implement this initializer
  init(map: Mapper) throws {
    try id = map.from("id")
    photoURL = map.optionalFrom("avatar_url")
  }
}

// Create a user!
let JSON: NSDictionary = ...
let user = User.from(JSON) // This is a 'User?'

Using with enums:

enum UserType: String {
  case Normal = "normal"
  case Admin = "admin"
}

struct User: Mappable {
  let id: String
  let type: UserType

  init(map: Mapper) throws {
    try id = map.from("id")
    try type = map.from("user_type")
  }
}

Nested Mappable objects:

struct User: Mappable {
  let id: String
  let name: String

  init(map: Mapper) throws {
    try id = map.from("id")
    try name = map.from("name")
  }
}

struct Group: Mappable {
  let id: String
  let users: [User]

  init(map: Mapper) throws {
    try id = map.from("id")
    users = map.optionalFrom("users") ?? []
  }
}

Use Convertible to transparently convert other types from JSON:

extension CLLocationCoordinate2D: Convertible {
  public static func fromMap(_ value: Any) throws -> CLLocationCoordinate2D {
    guard let location = value as? NSDictionary,
      let latitude = location["lat"] as? Double,
      let longitude = location["lng"] as? Double else
      {
         throw MapperError.convertibleError(value: value, type: [String: Double].self)
      }

      return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
  }
}

struct Place: Mappable {
  let name: String
  let location: CLLocationCoordinate2D

  init(map: Mapper) throws {
    try name = map.from("name")
    try location = map.from("location")
  }
}

let JSON: NSDictionary = [
  "name": "Lyft HQ",
  "location": [
    "lat": 37.7603392,
    "lng": -122.41267249999999,
  ],
]

let place = Place.from(JSON)

Custom Transformations

private func extractFirstName(object: Any?) throws -> String {
  guard let fullName = object as? String else {
    throw MapperError.convertibleError(value: object, type: String.self)
  }

  let parts = fullName.characters.split { $0 == " " }.map(String.init)
  if let firstName = parts.first {
    return firstName
  }

  throw MapperError.customError(field: nil, message: "Couldn't split the string!")
}

struct User: Mappable {
  let firstName: String

  init(map: Mapper) throws {
    try firstName = map.from("name", transformation: extractFirstName)
  }
}

Parse nested or entire objects

struct User: Mappable {
  let name: String
  let JSON: AnyObject

  init(map: Mapper) throws {
    // Access the 'first' key nested in a 'name' dictionary
    try name = map.from("name.first")
    // Access the original JSON (maybe for use with a transformation)
    try JSON = map.from("")
  }
}

See the docstrings and tests for more information and examples.

Open Radars

These radars have affected the current implementation of Mapper

  • rdar://23376350 Protocol extensions with initializers do not work in extensions
  • rdar://23358609 Protocol extensions with initializers do not play well with classes
  • rdar://23226135 Can't conform to protocols with similar generic function signatures
  • rdar://23147654 Generic functions are not differentiated by their ability to throw
  • rdar://23695200 Using the ?? operator many times is unsustainable.
  • rdar://23697280 Lazy collection elements can be evaluated multiple times.
  • rdar://23718307 Non final class with protocol extensions returning Self don't work

License

Mapper is maintained by Lyft and released under the Apache 2.0 license. See LICENSE for details

More Repositories

1

cartography

Cartography is a Python tool that consolidates infrastructure assets and the relationships between them in an intuitive graph view powered by a Neo4j database.
Python
2,856
star
2

scissors

โœ‚ Android image cropping library
Java
1,841
star
3

confidant

Confidant: your secret keeper. https://lyft.github.io/confidant
Python
1,781
star
4

clutch

Extensible platform for infrastructure management
Go
1,610
star
5

react-javascript-to-typescript-transform

Convert React JavaScript code to TypeScript with proper typing
TypeScript
1,574
star
6

scoop

๐Ÿฆ micro framework for building view based modular Android applications.
Java
1,036
star
7

Hammer

iOS touch synthesis library
Swift
642
star
8

protoc-gen-star

protoc plugin library for efficient proto-based code generation
Go
563
star
9

xiblint

A tool for linting storyboard and xib files
Python
522
star
10

flinkk8soperator

Kubernetes operator that provides control plane for managing Apache Flink applications
Go
508
star
11

domic

Reactive Virtual DOM for Android.
Kotlin
482
star
12

metadataproxy

A proxy for AWS's metadata service that gives out scoped IAM credentials from STS
Python
450
star
13

cni-ipvlan-vpc-k8s

AWS VPC Kubernetes CNI driver using IPvlan
Go
357
star
14

nuscenes-devkit

Devkit for the public 2019 Lyft Level 5 AV Dataset (fork of https://github.com/nutonomy/nuscenes-devkit)
Jupyter Notebook
352
star
15

presto-gateway

A load balancer / proxy / gateway for prestodb
JavaScript
337
star
16

toasted-marshmallow

S'More speed for Marshmallow
Python
297
star
17

Kronos-Android

An Open Source Kotlin SNTP library
Kotlin
239
star
18

coloralgorithm

Javacript function to produce color sets
JavaScript
225
star
19

awspricing

Python library for AWS pricing.
Python
201
star
20

discovery

This service provides a REST interface for querying for the list of hosts that belong to all microservices.
Python
185
star
21

linty_fresh

โœจ Surface lint errors during code review
Python
183
star
22

universal-async-component

React Universal Async Component that works with server side rendering
TypeScript
180
star
23

swift-index-store

Library to read from Swift / clang source code indexes
C++
123
star
24

python-blessclient

Python client for fetching BLESS certificates
Python
112
star
25

goruntime

Go client for Runtime application level feature flags and configuration
Go
84
star
26

omnibot

One slackbot to rule them all
Python
80
star
27

lyft-android-sdk

Public Lyft SDK for Android
Java
72
star
28

high-entropy-string

A library for classifying strings as potential secrets.
Python
60
star
29

gostats

Go client for Stats
Go
56
star
30

pynamodb-attributes

Common attributes for PynamoDB
Python
52
star
31

bandit-high-entropy-string

A high entropy string plugin for OpenStack's bandit project
Python
48
star
32

Lyft-iOS-sdk

Public Lyft SDK for iOS
Swift
43
star
33

python-kmsauth

A python library for reusing KMS for your own authentication and authorization
Python
38
star
34

opsreview

Compile a report of recent PagerDuty alerts for a single escalation policy.
Python
29
star
35

atlantis

Terraform automation for GitHub PRs (private fork of runatlantis/atlantis)
Go
18
star
36

lyft-node-sdk

Node SDK for the Lyft Public API
JavaScript
16
star
37

fake_sqs

An implementation of a local SQS service.
Ruby
15
star
38

lyft.github.io

This is code for oss.lyft.com website.
TypeScript
14
star
39

dockernetes

Run kubernetes inside a docker container.
Dockerfile
12
star
40

python-confidant-client

Client library and CLI for Confidant
Python
11
star
41

kustomizer

A container for running k8s kustomize
Shell
11
star
42

collectd-statsd

collectd plugin to write to statsd
Python
10
star
43

lyft-web-button

Build an actionable, Lyft-branded button for your website
JavaScript
9
star
44

dynamodb-hive-serde

Hive Deserializer for DynamoDB backup data format
Java
8
star
45

syx

Python 2 and 3 compatibility library from Lyft.
Python
7
star
46

lyft-node-samples

Sample applications using Node.js for the Lyft Public API
JavaScript
7
star
47

android-puzzlers

Android puzzles for Lyft Talks and more.
Java
6
star
48

lyft-go-sdk

Go SDK for the Lyft Public API
Go
6
star
49

lyft-django-sample

An API integration example using Django and social-auth.
Python
5
star
50

python-omnibot-receiver

Library for use by services that receive messages from omnibot.
Python
4
star
51

osscla

Open Source Contributor License Agreement service
Python
4
star
52

code-of-conduct

Code of Conduct for Lyft's open source projects
3
star
53

CLA

Contributor License Agreement (CLA) for Lyft's open source projects
3
star
54

awseipext

AWS Lambda that extends the EC2 Elastic IP API
Python
3
star
55

heroku-buildpack-php

Shell
2
star
56

lyft-go-samples

Sample applications in Go for the Lyft Public API
Go
1
star
57

flask-pystatsd

flask extension to simplify the use of the pystatsd library
Python
1
star
58

eventbot

A slackbot to help organize events
Python
1
star