GithubHelp home page GithubHelp logo

alibaba / handyjson Goto Github PK

View Code? Open in Web Editor NEW
4.2K 77.0 598.0 541 KB

A handy swift json-object serialization/deserialization library

License: Other

Ruby 0.27% Swift 98.89% Shell 0.50% C 0.34%
swift json serialization json-fields deserialization mapping

handyjson's Introduction

HandyJSON

To deal with crash on iOS 15 beta3 please try version 5.0.4-beta

HandyJSON is a framework written in Swift which to make converting model objects( pure classes/structs ) to and from JSON easy on iOS.

Compared with others, the most significant feature of HandyJSON is that it does not require the objects inherit from NSObject(not using KVC but reflection), neither implements a 'mapping' function(writing value to memory directly to achieve property assignment).

HandyJSON is totally depend on the memory layout rules infered from Swift runtime code. We are watching it and will follow every bit if it changes.

Build Status Carthage compatible Cocoapods Version Cocoapods Platform Codecov branch

交流群

群号: 581331250

交流群

Sample Code

Deserialization

class BasicTypes: HandyJSON {
    var int: Int = 2
    var doubleOptional: Double?
    var stringImplicitlyUnwrapped: String!

    required init() {}
}

let jsonString = "{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}"
if let object = BasicTypes.deserialize(from: jsonString) {
    print(object.int)
    print(object.doubleOptional!)
    print(object.stringImplicitlyUnwrapped)
}

Serialization

let object = BasicTypes()
object.int = 1
object.doubleOptional = 1.1
object.stringImplicitlyUnwrapped = “hello"

print(object.toJSON()!) // serialize to dictionary
print(object.toJSONString()!) // serialize to JSON string
print(object.toJSONString(prettyPrint: true)!) // serialize to pretty JSON string

Content

Features

  • Serialize/Deserialize Object/JSON to/From JSON/Object

  • Naturally use object property name for mapping, no need to specify a mapping relationship

  • Support almost all types in Swift, including enum

  • Support struct

  • Custom transformations

  • Type-Adaption, such as string json field maps to int property, int json field maps to string property

An overview of types supported can be found at file: BasicTypes.swift

Requirements

  • iOS 8.0+/OSX 10.9+/watchOS 2.0+/tvOS 9.0+

  • Swift 3.0+ / Swift 4.0+ / Swift 5.0+

Installation

To use with Swift 5.0/5.1 ( Xcode 10.2+/11.0+ ), version == 5.0.2

To use with Swift 4.2 ( Xcode 10 ), version == 4.2.0

To use with Swift 4.0, version >= 4.1.1

To use with Swift 3.x, version >= 1.8.0

For Legacy Swift2.x support, take a look at the swift2 branch.

Cocoapods

Add the following line to your Podfile:

pod 'HandyJSON', '~> 5.0.2'

Then, run the following command:

$ pod install

Carthage

You can add a dependency on HandyJSON by adding the following line to your Cartfile:

github "alibaba/HandyJSON" ~> 5.0.2

Manually

You can integrate HandyJSON into your project manually by doing the following steps:

  • Open up Terminal, cd into your top-level project directory, and add HandyJSON as a submodule:
git init && git submodule add https://github.com/alibaba/HandyJSON.git
  • Open the new HandyJSON folder, drag the HandyJSON.xcodeproj into the Project Navigator of your project.

  • Select your application project in the Project Navigator, open the General panel in the right window.

  • Click on the + button under the Embedded Binaries section.

  • You will see two different HandyJSON.xcodeproj folders each with four different versions of the HandyJSON.framework nested inside a Products folder.

It does not matter which Products folder you choose from, but it does matter which HandyJSON.framework you choose.

  • Select one of the four HandyJSON.framework which matches the platform your Application should run on.

  • Congratulations!

Deserialization

The Basics

To support deserialization from JSON, a class/struct need to conform to 'HandyJSON' protocol. It's truly protocol, not some class inherited from NSObject.

To conform to 'HandyJSON', a class need to implement an empty initializer.

class BasicTypes: HandyJSON {
    var int: Int = 2
    var doubleOptional: Double?
    var stringImplicitlyUnwrapped: String!

    required init() {}
}

let jsonString = "{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}"
if let object = BasicTypes.deserialize(from: jsonString) {
    // …
}

Support Struct

For struct, since the compiler provide a default empty initializer, we use it for free.

struct BasicTypes: HandyJSON {
    var int: Int = 2
    var doubleOptional: Double?
    var stringImplicitlyUnwrapped: String!
}

let jsonString = "{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}"
if let object = BasicTypes.deserialize(from: jsonString) {
    // …
}

But also notice that, if you have a designated initializer to override the default one in the struct, you should explicitly declare an empty one(no required modifier need).

Support Enum Property

To be convertable, An enum must conform to HandyJSONEnum protocol. Nothing special need to do now.

enum AnimalType: String, HandyJSONEnum {
    case Cat = "cat"
    case Dog = "dog"
    case Bird = "bird"
}

struct Animal: HandyJSON {
    var name: String?
    var type: AnimalType?
}

let jsonString = "{\"type\":\"cat\",\"name\":\"Tom\"}"
if let animal = Animal.deserialize(from: jsonString) {
    print(animal.type?.rawValue)
}

Optional/ImplicitlyUnwrappedOptional/Collections/...

'HandyJSON' support classes/structs composed of optional, implicitlyUnwrappedOptional, array, dictionary, objective-c base type, nested type etc. properties.

class BasicTypes: HandyJSON {
    var bool: Bool = true
    var intOptional: Int?
    var doubleImplicitlyUnwrapped: Double!
    var anyObjectOptional: Any?

    var arrayInt: Array<Int> = []
    var arrayStringOptional: Array<String>?
    var setInt: Set<Int>?
    var dictAnyObject: Dictionary<String, Any> = [:]

    var nsNumber = 2
    var nsString: NSString?

    required init() {}
}

let object = BasicTypes()
object.intOptional = 1
object.doubleImplicitlyUnwrapped = 1.1
object.anyObjectOptional = "StringValue"
object.arrayInt = [1, 2]
object.arrayStringOptional = ["a", "b"]
object.setInt = [1, 2]
object.dictAnyObject = ["key1": 1, "key2": "stringValue"]
object.nsNumber = 2
object.nsString = "nsStringValue"

let jsonString = object.toJSONString()!

if let object = BasicTypes.deserialize(from: jsonString) {
    // ...
}

Designated Path

HandyJSON supports deserialization from designated path of JSON.

class Cat: HandyJSON {
    var id: Int64!
    var name: String!

    required init() {}
}

let jsonString = "{\"code\":200,\"msg\":\"success\",\"data\":{\"cat\":{\"id\":12345,\"name\":\"Kitty\"}}}"

if let cat = Cat.deserialize(from: jsonString, designatedPath: "data.cat") {
    print(cat.name)
}

Composition Object

Notice that all the properties of a class/struct need to deserialized should be type conformed to HandyJSON.

class Component: HandyJSON {
    var aInt: Int?
    var aString: String?

    required init() {}
}

class Composition: HandyJSON {
    var aInt: Int?
    var comp1: Component?
    var comp2: Component?

    required init() {}
}

let jsonString = "{\"num\":12345,\"comp1\":{\"aInt\":1,\"aString\":\"aaaaa\"},\"comp2\":{\"aInt\":2,\"aString\":\"bbbbb\"}}"

if let composition = Composition.deserialize(from: jsonString) {
    print(composition)
}

Inheritance Object

A subclass need deserialization, it's superclass need to conform to HandyJSON.

class Animal: HandyJSON {
    var id: Int?
    var color: String?

    required init() {}
}

class Cat: Animal {
    var name: String?

    required init() {}
}

let jsonString = "{\"id\":12345,\"color\":\"black\",\"name\":\"cat\"}"

if let cat = Cat.deserialize(from: jsonString) {
    print(cat)
}

JSON Array

If the first level of a JSON text is an array, we turn it to objects array.

class Cat: HandyJSON {
    var name: String?
    var id: String?

    required init() {}
}

let jsonArrayString: String? = "[{\"name\":\"Bob\",\"id\":\"1\"}, {\"name\":\"Lily\",\"id\":\"2\"}, {\"name\":\"Lucy\",\"id\":\"3\"}]"
if let cats = [Cat].deserialize(from: jsonArrayString) {
    cats.forEach({ (cat) in
        // ...
    })
}

Mapping From Dictionary

HandyJSON support mapping swift dictionary to model.

var dict = [String: Any]()
dict["doubleOptional"] = 1.1
dict["stringImplicitlyUnwrapped"] = "hello"
dict["int"] = 1
if let object = BasicTypes.deserialize(from: dict) {
    // ...
}

Custom Mapping

HandyJSON let you customize the key mapping to JSON fields, or parsing method of any property. All you need to do is implementing an optional mapping function, do things in it.

We bring the transformer from ObjectMapper. If you are familiar with it, it’s almost the same here.

class Cat: HandyJSON {
    var id: Int64!
    var name: String!
    var parent: (String, String)?
    var friendName: String?

    required init() {}

    func mapping(mapper: HelpingMapper) {
        // specify 'cat_id' field in json map to 'id' property in object
        mapper <<<
            self.id <-- "cat_id"

        // specify 'parent' field in json parse as following to 'parent' property in object
        mapper <<<
            self.parent <-- TransformOf<(String, String), String>(fromJSON: { (rawString) -> (String, String)? in
                if let parentNames = rawString?.characters.split(separator: "/").map(String.init) {
                    return (parentNames[0], parentNames[1])
                }
                return nil
            }, toJSON: { (tuple) -> String? in
                if let _tuple = tuple {
                    return "\(_tuple.0)/\(_tuple.1)"
                }
                return nil
            })

        // specify 'friend.name' path field in json map to 'friendName' property
        mapper <<<
            self.friendName <-- "friend.name"
    }
}

let jsonString = "{\"cat_id\":12345,\"name\":\"Kitty\",\"parent\":\"Tom/Lily\",\"friend\":{\"id\":54321,\"name\":\"Lily\"}}"

if let cat = Cat.deserialize(from: jsonString) {
    print(cat.id)
    print(cat.parent)
    print(cat.friendName)
}

Date/Data/URL/Decimal/Color

HandyJSON prepare some useful transformer for some none-basic type.

class ExtendType: HandyJSON {
    var date: Date?
    var decimal: NSDecimalNumber?
    var url: URL?
    var data: Data?
    var color: UIColor?

    func mapping(mapper: HelpingMapper) {
        mapper <<<
            date <-- CustomDateFormatTransform(formatString: "yyyy-MM-dd")

        mapper <<<
            decimal <-- NSDecimalNumberTransform()

        mapper <<<
            url <-- URLTransform(shouldEncodeURLString: false)

        mapper <<<
            data <-- DataTransform()

        mapper <<<
            color <-- HexColorTransform()
    }

    public required init() {}
}

let object = ExtendType()
object.date = Date()
object.decimal = NSDecimalNumber(string: "1.23423414371298437124391243")
object.url = URL(string: "https://www.aliyun.com")
object.data = Data(base64Encoded: "aGVsbG8sIHdvcmxkIQ==")
object.color = UIColor.blue

print(object.toJSONString()!)
// it prints:
// {"date":"2017-09-11","decimal":"1.23423414371298437124391243","url":"https:\/\/www.aliyun.com","data":"aGVsbG8sIHdvcmxkIQ==","color":"0000FF"}

let mappedObject = ExtendType.deserialize(from: object.toJSONString()!)!
print(mappedObject.date)
...

Exclude Property

If any non-basic property of a class/struct could not conform to HandyJSON/HandyJSONEnum or you just do not want to do the deserialization with it, you should exclude it in the mapping function.

class NotHandyJSONType {
    var dummy: String?
}

class Cat: HandyJSON {
    var id: Int64!
    var name: String!
    var notHandyJSONTypeProperty: NotHandyJSONType?
    var basicTypeButNotWantedProperty: String?

    required init() {}

    func mapping(mapper: HelpingMapper) {
        mapper >>> self.notHandyJSONTypeProperty
        mapper >>> self.basicTypeButNotWantedProperty
    }
}

let jsonString = "{\"name\":\"cat\",\"id\":\"12345\"}"

if let cat = Cat.deserialize(from: jsonString) {
    print(cat)
}

Update Existing Model

HandyJSON support updating an existing model with given json string or dictionary.

class BasicTypes: HandyJSON {
    var int: Int = 2
    var doubleOptional: Double?
    var stringImplicitlyUnwrapped: String!

    required init() {}
}

var object = BasicTypes()
object.int = 1
object.doubleOptional = 1.1

let jsonString = "{\"doubleOptional\":2.2}"
JSONDeserializer.update(object: &object, from: jsonString)
print(object.int)
print(object.doubleOptional)

Supported Property Type

  • Int/Bool/Double/Float/String/NSNumber/NSString

  • RawRepresentable enum

  • NSArray/NSDictionary

  • Int8/Int16/Int32/Int64/UInt8/UInt16/UInt23/UInt64

  • Optional<T>/ImplicitUnwrappedOptional<T> // T is one of the above types

  • Array<T> // T is one of the above types

  • Dictionary<String, T> // T is one of the above types

  • Nested of aboves

Serialization

The Basics

Now, a class/model which need to serialize to JSON should also conform to HandyJSON protocol.

class BasicTypes: HandyJSON {
    var int: Int = 2
    var doubleOptional: Double?
    var stringImplicitlyUnwrapped: String!

    required init() {}
}

let object = BasicTypes()
object.int = 1
object.doubleOptional = 1.1
object.stringImplicitlyUnwrapped = “hello"

print(object.toJSON()!) // serialize to dictionary
print(object.toJSONString()!) // serialize to JSON string
print(object.toJSONString(prettyPrint: true)!) // serialize to pretty JSON string

Mapping And Excluding

It’s all like what we do on deserialization. A property which is excluded, it will not take part in neither deserialization nor serialization. And the mapper items define both the deserializing rules and serializing rules. Refer to the usage above.

FAQ

Q: Why the mapping function is not working in the inheritance object?

A: For some reason, you should define an empty mapping function in the super class(the root class if more than one layer), and override it in the subclass.

It's the same with didFinishMapping function.

Q: Why my didSet/willSet is not working?

A: Since HandyJSON assign properties by writing value to memory directly, it doesn't trigger any observing function. You need to call the didSet/willSet logic explicitly after/before the deserialization.

But since version 1.8.0, HandyJSON handle dynamic properties by the KVC mechanism which will trigger the KVO. That means, if you do really need the didSet/willSet, you can define your model like follow:

class BasicTypes: NSObject, HandyJSON {
    dynamic var int: Int = 0 {
        didSet {
            print("oldValue: ", oldValue)
        }
        willSet {
            print("newValue: ", newValue)
        }
    }

    public override required init() {}
}

In this situation, NSObject and dynamic are both needed.

And in versions since 1.8.0, HandyJSON offer a didFinishMapping function to allow you to fill some observing logic.

class BasicTypes: HandyJSON {
    var int: Int?

    required init() {}

    func didFinishMapping() {
        print("you can fill some observing logic here")
    }
}

It may help.

Q: How to support Enum property?

It your enum conform to RawRepresentable protocol, please look into Support Enum Property. Or use the EnumTransform:

enum EnumType: String {
    case type1, type2
}

class BasicTypes: HandyJSON {
    var type: EnumType?

    func mapping(mapper: HelpingMapper) {
        mapper <<<
            type <-- EnumTransform()
    }

    required init() {}
}

let object = BasicTypes()
object.type = EnumType.type2
print(object.toJSONString()!)
let mappedObject = BasicTypes.deserialize(from: object.toJSONString()!)!
print(mappedObject.type)

Otherwise, you should implement your custom mapping function.

enum EnumType {
    case type1, type2
}

class BasicTypes: HandyJSON {
    var type: EnumType?

    func mapping(mapper: HelpingMapper) {
        mapper <<<
            type <-- TransformOf<EnumType, String>(fromJSON: { (rawString) -> EnumType? in
                if let _str = rawString {
                    switch (_str) {
                    case "type1":
                        return EnumType.type1
                    case "type2":
                        return EnumType.type2
                    default:
                        return nil
                    }
                }
                return nil
            }, toJSON: { (enumType) -> String? in
                if let _type = enumType {
                    switch (_type) {
                    case EnumType.type1:
                        return "type1"
                    case EnumType.type2:
                        return "type2"
                    }
                }
                return nil
            })
    }

    required init() {}
}

Credit

  • reflection: After the first version which used the swift mirror mechanism, HandyJSON had imported the reflection library and rewrote some code for class properties inspecting.
  • ObjectMapper: To make HandyJSON more compatible with the general style, the Mapper function support Transform which designed by ObjectMapper. And we import some testcases from ObjectMapper.

License

HandyJSON is released under the Apache License, Version 2.0. See LICENSE for details.

handyjson's People

Contributors

alibaba-oss avatar cijianzy avatar codetalks-new avatar crwnet avatar felipericieri avatar happyxb avatar henrs avatar iosdevzone avatar khasinski avatar lanmaoxinqing avatar levanlongktmt avatar lynnleelhl avatar mewehk avatar spicyshrimp avatar swwlqw avatar wongzigii avatar xuyecan 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

handyjson's Issues

序列化之后不能反序列化

json串是用HandyJSON产生的。
json串如下:
{"Height":"5.1181","Material":"Face: 100% cotton texture fabric with pearl stitching, 100% cotton texture fabric reverse","PrimaryColor":"Blue","ItemNo":"WR11-1133","RetailPrice":"15.39","SalesPrice":"15.39","SizeName":"Euro Sham","RetailItemInvLocRelation":"[Olliix.ItemInvLoc]","SizeDescription":"26"x26",","AllColors":"["Blue"]","Colors":"["Blue"]","Width":"6.1024","Product_ID":"4504","PicPath":"/Woolrich Lake side Euro silo.jpg","Description":"Blue cotton textured fabric with pearl stitching.","SetIncludes":"1 Euro Sham,","Qty":1,"CareInstructions":"MACHINE WASH COLD, GENTLE CYCLE, AND SEPARATELY. DO NOT BLEACH. TUMBLE DRY LOW, REMOVE PROMPTLY. DO NOT IRON. IF THERE IS NO FREE MOVEMENT IN THE WASHER OR DRYER, USE LARGE CAPACITY COMMERCIAL WASHER/DRYER.","AllSizes":"["Euro Sham"]","PrimarySize":"Euro Sham","Length":"9.8425","ProductName":"Lake Side Euro Sham","UPC":"675716504724","RetailBrandName":"Woolrich"}

Problem when serializing to simple Dictionnary with Enum

Hello,
when sending my serialized object in my URLRequest with Alamofire,
my REST API didn't worked and the log said : "NSInvalidArgumentException [blah blah] JSON(write)".
I have used the toSimpleDictionary() func to send my json object.
I figured out that my object contained an enum and that when it is serialized the enum
is transforming into "MyModule.MyEnum.Value" instead of "Value".
To illustrate this clearly, see the class

class MyObject: HandyJSON {
 var someInfo: String?
 var myEnum: MyEnum?

 required init() {}
}

see the enum

enum MyEnum: HandyJSONEnum {
 case MyValue
 case MyOtherValue

 static func makeInitWrapper() -> InitWrapperProtocol? {
        return InitWrapper<String>(rawInit: MyEnum.init)
 }
}

see example of use

let myObject = MyObject()
request.someInfos = "some useful infos"
request.myEnum = MyEnum.MyValue
var urlRequest = URLRequest(url: "myURL")
urlRequest = try JSONEncoding.default.encode(urlRequest, with: myObject.toSimpleDictionary())
Alamofire.request(urlRequest)

My solution is to modify JSONSerializer.swift

extension GenericObjectTransformer {
 static func transformToSimpleObject(object: Any) -> Any? {
 // ...
 case enum:
  return String(describing: object) as Any
 // ...
 }
}

i'm aware that in this case, the result of your func will not be a pure "object"
but it will match my REST API regardless of the module name or enum name,
just the value is needed (a string in my case, i didn't try an int or something else).
What do you think ?

手动安装失败

使用cocopods可以安装,但是手动安装失败,提示Use of unresolved identifier 'JSONSerialization'等错误,请问手动安装可以更简单点吗,感觉有点麻烦,谢谢

现在使用carthage安装成功了,谢谢了哈

Xcode8.1编译报错

/Pods/HandyJSON/HandyJSON/Property.swift:404:86: Cannot assign to property: 'pointee' is a get-only property

当model中某个String变量,存的是json字符格式解析不出来

当model中某个String变量,存的是json字符格式解析不出来

struct DemoStruct: HandyJSON {
    var body: String = "{\"body\":\"123\"}"
    var name: String = "name"
}

let requestStr = JSONSerializer.serializeToJSON(object: DemoStruct())
            if requestStr != nil {
                print(requestStr!)
            }
            if let req = JSONDeserializer<DemoStruct>.deserializeFrom(json: requestStr) {
                print(req)
            } else {
                print("Error")
            }

Manual Installation

CocoaPods and Carthage are awesome tools and make our life really easier, but there are some devs who still don't know how to use them.

It would be cool to add the Manual installation guide in your README.md. You can take a look at my iOS Readme Template to see how you can do it.

当类型中存在Date类型的字段时, 序列化失败

当类型中存在Date类型的字段时, 序列化失败
并且当json字符串中含有Date类型的字段时, 反序列化为对象后, 对象内的Date类型也是nil
请查看一下代码:

import UIKit
import HandyJSON


class Temp: HandyJSON {
    var name:String?
    var date:Date?
    required init(){
        name = "df"
        date = Date.init(timeIntervalSinceNow: 0)
    }
}

let json = Temp().toJSONString()
let r = JSONDeserializer<Temp>.deserializeFrom(json: json)
print(json)
print(r?.name)
print(r?.date)

Carthage warning

/Users/songlijun/Study/iOS/HandyJSONDemo/Carthage/Checkouts/HandyJSON/HandyJSON/JSONSerializer.swift:60:82: warning: expression implicitly coerced from 'Any?' to Any
/Users/songlijun/Study/iOS/HandyJSONDemo/Carthage/Checkouts/HandyJSON/HandyJSON/JSONSerializer.swift:67:82: warning: expression implicitly coerced from 'Any?' to Any
/Users/songlijun/Study/iOS/HandyJSONDemo/Carthage/Checkouts/HandyJSON/HandyJSON/JSONSerializer.swift:74:82: warning: expression implicitly coerced from 'Any?' to Any
/Users/songlijun/Study/iOS/HandyJSONDemo/Carthage/Checkouts/HandyJSON/HandyJSON/JSONSerializer.swift:60:82: warning: expression implicitly coerced from 'Any?' to Any
/Users/songlijun/Study/iOS/HandyJSONDemo/Carthage/Checkouts/HandyJSON/HandyJSON/JSONSerializer.swift:67:82: warning: expression implicitly coerced from 'Any?' to Any
/Users/songlijun/Study/iOS/HandyJSONDemo/Carthage/Checkouts/HandyJSON/HandyJSON/JSONSerializer.swift:74:82: warning: expression implicitly coerced from 'Any?' to Any
/Users/songlijun/Study/iOS/HandyJSONDemo/Carthage/Checkouts/HandyJSON/HandyJSON/JSONSerializer.swift:60:82: warning: expression implicitly coerced from 'Any?' to Any
/Users/songlijun/Study/iOS/HandyJSONDemo/Carthage/Checkouts/HandyJSON/HandyJSON/JSONSerializer.swift:67:82: warning: expression implicitly coerced from 'Any?' to Any
/Users/songlijun/Study/iOS/HandyJSONDemo/Carthage/Checkouts/HandyJSON/HandyJSON/JSONSerializer.swift:74:82: warning: expression implicitly coerced from 'Any?' to Any
/Users/songlijun/Study/iOS/HandyJSONDemo/Carthage/Checkouts/HandyJSON/HandyJSON/JSONSerializer.swift:60:82: warning: expression implicitly coerced from 'Any?' to Any
/Users/songlijun/Study/iOS/HandyJSONDemo/Carthage/Checkouts/HandyJSON/HandyJSON/JSONSerializer.swift:67:82: warning: expression implicitly coerced from 'Any?' to Any
/Users/songlijun/Study/iOS/HandyJSONDemo/Carthage/Checkouts/HandyJSON/HandyJSON/JSONSerializer.swift:74:82: warning: expression implicitly coerced from 'Any?' to Any

Undefined symbols for architecture i386:

用cocoapods加载的HandyJSON(1.2.1),swift 3.0, xcode 8.0, iOS 9.0;在“模拟机”的iPhone5上会提示
Undefined symbols for architecture i386:的错误

这种嵌套结构是否可以解析,我一直解析失败

{
  "artists": [
    {
      "name": "Pablo Picasso",
      "bio": "Pablo Ruiz y Picasso (25 October 1881 – 8 April 1973), also known as Pablo Picasso, was a Spanish painter, sculptor, printmaker, ceramicist, stage designer, poet and playwright who spent most of his adult life in France.",
      "image": "0",
      "works": [
        {
          "title": "Guernica",
          "image": "Picasso1",
          "info": "Guern y violence and chaos."
        },
        {
          "title": "The Weeping Woman",
          "image": "Picasso2",
          "info": "The Weeping Woman,  Modern, London."
        },
        {
          "title": "L'Homme aux cartes (Card Player)",
          "image": "Picasso3",
          "info": "1913–14, Museum of Modern Art, New York"
        },
        {
          "title": "Asleep",
          "image": "Picasso4",
          "info": "The model of this painting, color blocks.(PabloPicasso.org)"
        }
      ]
    },
    {
      "name": "Rembrandt",
      "bio": " Dutch history.",
      "image": "6",
      "works": [
        {
          "title": "Belshazzar's Feast",
          "image": "Rembrandt1",
          "info": " a painter of large, baroque history paintings."
        },
        {
          "title": "The Night Watch",
          "image": "Rembrandt2",
          "info": "s collection."
        },
        {
          "title": "Syndics of the Drapers' Guild",
          "image": "Rembrandt3",
          "info": "The Samplingrapers' Guild, is a 1662 oilportrait'."
        },
        {
          "title": "Jacob de Gheyn III",
          "image": "Rembrandt4",
          "info": ", wearing similar clothing (ruffs and black doublets) and facing the opposite direction."
        }
      ]
    }
  ]
}

小问题

能不能写一个把model转换成字典或者数组的方法,有时候可能会用到.为什么类里面要实现这个required init() {}.

sub class object missed during deserialization

prettify json string: {
"_id" : "582d633ef1a0b90950782205",
"authorId" : {
"nickname" : "p1别名",
"_id" : "582c549d0bd653ad5fb04336",
"username" : "p1",
"avatar" : "remote_default_user.png"
},
"commentIds" : [

],
"placeName" : "上海",
"content" : "testContent2",
"createdTime" : 1234567891,
"tag" : "art",
"relatedUserIds" : [

],
"image" : "1478704739.71422",
"loc" : [
121.456748,
31.262244
],
"read" : 0
}

after deserialization
authorId: nil
commentIds: nil
relatedUserIds: nil

how can i get the above three field back?

Thanks in advance!

crash

json: {"body":""}

if let req = JSONDeserializer<T>.deserializeFrom(json: "{\"body\":\"\"}") {
                print(req)
            }

HandyJSON/Property.swift, line 164

1.5.0 的更新中存在一个bug

当使用继承, 并在子类型中使用泛型时, 序列化失败
请在playground中运行以下代码:

import UIKit
import HandyJSON

class ResultBase: HandyJSON {
    
    var message:String = "未知错误"
    
    required init(){}
}

class ResultBase1<T>: ResultBase {
    
    var obj:T?
}

var json = JSONDeserializer<ResultBase>.deserializeFrom(json: "{\"obj\":null,\"code\":0,\"message\":\"密码不正确!\",\"success\":false}")!
print(json.message)  \\输出: 密码不正确
print()

json = JSONDeserializer<ResultBase1<String?>>.deserializeFrom(json: "{\"obj\":null,\"code\":0,\"message\":\"密码不正确!\",\"success\":false}")!
print(json.message) \\输出: 未知错误
print()


var result = ResultBase1<String?>()
result.message = "密码不正确"
var obj = JSONDeserializer<ResultBase1<String?>>.deserializeFrom(json: result.toJSONString())!
\\输出: Can not find offset info for property: message
print(obj.message) \\输出: 未知错误

mapper.specify用法请教

class Knowledge : HandyJSON{
    var title: String?
    var desc: String?
    var exercises:[Exercise]?
    required init() {}
    
    func mapping(mapper: HelpingMapper) {
        // 指定 JSON中的`tests`字段映射到Model中的`exercises`字段
        mapper.specify(property: &exercises, name: "tests")
    }
}

在实际使用过程中,json字符串中的tests并没有映射到exercises,是我的用法不对么?

Support Linux

I want to use it in server side, can this project support Linux?

能否实现Int到String的自动转换

有时候服务端下发的id可能是Int也可能是String
很多时候客户端其实不关心这个类型,只是用于展示数据
对于JSON中的Int数据,反序列化时接收者如果是String能否自动做转化

struct can't have designated initializer.

For a struct, if it has any designated initializer, compiler will complaint that:
type does not conform to protocol 'HandyJSON'.

For example, this struct can't pass compiler:

struct Animal: HandyJSON {
    var name: String?
    var id: String?
    var num: Int?

    init(name: String?, id: String?, num: Int?) {
        self.name = name
        self.id = id
        self.num = num
    }
}

I'm not quite sure if this is a bug.

对枚举类型的实现效果不佳

我们通常会针对服务端下发的数字转化成枚举
enum ResourceType : Int {
case 新闻 = 1
case 自媒体 = 2
case 帖子 = 3
case 问答 = 4
case 话题 = 5
case Unknown = -1
}
在ObjectMapper里只要直接放上去这个,在用默认map就可以反序列化
初始化默认使用Unknown, 当服务端下发6,7等客户端无法识别的类型时还是会保存Unknown不变
HandyJSON能否实现类似效果,另外HandyJSON这个协议加到enum上会有入侵性

How to specify mapper for serialization?

When I try to serialize a Date and some custom fields. Serializing a Date crashes, and I don't see how to provide a serialization mapper. Am I missing something or is it a missing feature?

换行符的问题 \n

因为项目的原因,我还在用 HandyJSON 2.x ,表示非常好用,感谢作者。
但在使用当中发现一个问题,如果键值项有换行符,(输入项里面输入回车,这个是很常见的),_serializeToJSON 后生成的json 字符串是错的。
因为正确的 json 键值中如果有换行符,键值应该是 \\n 也就是字符 \ 和 字符n, 但, _serializeToJSON 后生成的json 是一个换行符\n
所以我做了以下修改, 不知道我理解得对不对。请大家指正

static func formatString(object: Any) -> String {
        var string = String(object)
        string = string.stringByReplacingOccurrencesOfString("\r", withString: "\\r")
        string = string.stringByReplacingOccurrencesOfString("\n", withString: "\\n")
        string = string.stringByReplacingOccurrencesOfString("\t", withString: "\\t")
  
        return string
        
    }

    static func _serializeToJSON(object: Any) -> String {

        if (object.dynamicType is String.Type || object.dynamicType is NSString.Type ) {
            let json = "\"" + formatString(object)  + "\""
            return json
        } else if (object.dynamicType is BasePropertyProtocol.Type) {
            let json = formatString(object) ?? "null"
            return json
        }

        var json = String()
        let mirror = Mirror(reflecting: object)

        if mirror.displayStyle == .Class || mirror.displayStyle == .Struct {
            var handledValue = String()
            var children = [(label: String?, value: Any)]()
            let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children)!
            children += mirrorChildrenCollection

            var currentMirror = mirror
            while let superclassChildren = currentMirror.superclassMirror()?.children {
                let randomCollection = AnyRandomAccessCollection(superclassChildren)!
                children += randomCollection
                currentMirror = currentMirror.superclassMirror()!
            }

            children.enumerate().forEach({ (index, element) in
                handledValue = _serializeToJSON(element.value)
                json += "\"\(element.label ?? "")\":\(handledValue)" + (index < children.count-1 ? "," : "")
            })

            return "{" + json + "}"
        } else if mirror.displayStyle == .Enum {
            return  "\"" + formatString(object) + "\""
        } else if  mirror.displayStyle == .Optional {
            if mirror.children.count != 0 {
                let (_, some) = mirror.children.first!
                return _serializeToJSON(some)
            } else {
                return "null"
            }
        } else if mirror.displayStyle == .Collection || mirror.displayStyle == .Set {
            json = "["

            let count = mirror.children.count
            mirror.children.enumerate().forEach({ (index, element) in
                let transformValue = _serializeToJSON(element.value)
                json += transformValue
                json += (index < count-1 ? "," : "")
            })

            json += "]"
            return json
        } else if mirror.displayStyle == .Dictionary {
            json += "{"
            mirror.children.enumerate().forEach({ (index, element) in
                let _mirror = Mirror(reflecting: element.value)
                _mirror.children.enumerate().forEach({ (_index, _element) in
                    if _index == 0 {
                        json += _serializeToJSON(_element.value) + ":"
                    } else {
                        json += _serializeToJSON(_element.value)
                        json += (index < mirror.children.count-1 ? "," : "")
                    }
                })
            })
            json += "}"
            return json
        } else {
            return formatString(object) != "nil" ? "\"\(object)\"" : "null"
        }
    }

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.