GithubHelp home page GithubHelp logo

evermeer / evreflection Goto Github PK

View Code? Open in Web Editor NEW
965.0 30.0 119.0 258.84 MB

Reflection based (Dictionary, CKRecord, NSManagedObject, Realm, JSON and XML) object mapping with extensions for Alamofire and Moya with RxSwift or ReactiveSwift

License: Other

Swift 98.63% Ruby 1.37%
swift evreflection json xml alamofire moya reactiveswift rxswift reflection objectmapper

evreflection's People

Contributors

amitaib avatar andrejjurkin avatar andrew-mace avatar bryant1410 avatar davidwu226 avatar dimillian avatar evermeer avatar gelemias avatar jon-cotton avatar joshua-greene avatar jrg-developer avatar jstheoriginal avatar kdvmgn avatar khasinski avatar kizitonwose avatar mortengregersen avatar multinerd avatar mxl avatar nbrice88 avatar pepasflo avatar rafcabezas avatar realenginerd avatar tylerlong avatar yogevsitton avatar zeushin 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

evreflection's Issues

NSDate issue

Hi, I'm sending to rest server a NSDate object.

if I print print(NSDate())

i get:
2016-01-18 15:35:43 +0000

after conversion with EVReflection i get:

"18/01/16, 16:35:49 CET",

this output is not compliant with standard because back end response is:

Can not construct instance of java.util.Date from String value '18/01/16, 16:35:49 CET': not a valid representation (error: Failed to parse Date value '18/01/16, 16:35:49 CET': Can not parse date "18/01/16, 16:35:49 CET": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))\n at

Generic Type

Hi,
I'im trying to parse jsonString to an object that contains a generic type but it's not working.
This is my example :

public class A<T: EVObject>: EVObject {

var test : String = ""
var test2 : String = ""
var data: T? = nil

}

public class B: EVObject {
var test3 : String = ""
var test4 : String = ""
}

Support custom Dictionary

I have some classes which look like this

class Document {
   var resources: [String: Resource]
}

class Resource {
 var id: String?
}

Is it natively supported by EVReflection ? Or should I implement a custom setValue ?

NSCoding should use all values (no propertyMapping of propertyConverters)

As discussed with @tbaggett

What is processed by NSCoding is the same as what's processed using the .toDictionary. So the propertyMapping will also be applied. Now I think of it, it might be a good idea to change the performKeyCleanup for that function to support more situations like:

raw - where everything comes pure from the Reflect
standard - where the propertyMapping and propertyConverter are executed
cleaned - where keywords, illegal characters, pascal, camel and snake case conversions are executed.
Then NSCoding should use the raw version since you want identical objects back.

"Array index out of range" Error in dictArrayToObjectArray

I have a test case that passes in 2.1.0 but throws a fatal error in 2.3.0. Let me know whether the fatal error thrown in 2.3.0 is expected behavior.

import UIKit
import XCTest

/**
Testing EVReflection for Json
*/
class ProfilePhotoUrlListTests: XCTestCase {

    /**
    For now nothing to setUp
    */
    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    /**
    For now nothing to tearDown
    */
    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }


    func testJsonObject(){

        let jsonDictOriginal = ["meta": ["limit": 1000, "offset": 0, "total_count": 4], "objects": [["id": 35, "index": 1, "resource_uri": "/api/v1/profilephotourl/35/", "url": "a", "user": "/api/v1/user/1/"], ["id": 37, "index": 0, "resource_uri": "/api/v1/profilephotourl/37/", "url": "b", "user": "/api/v1/user/1/"], ["id": 36, "index": 3, "resource_uri": "/api/v1/profilephotourl/36/", "url": "c", "user": "/api/v1/user/1/"], ["id": 44, "index": 2, "resource_uri": "/api/v1/profilephotourl/44/", "url": "d", "user": "/api/v1/user/1/"]]]

        print("Initial dictionary:\n\(jsonDictOriginal)\n\n")

        let profilePhotoUrlListOriginal = ProfilePhotoUrlList(dictionary: jsonDictOriginal)
        print("Dictionary to an object: \n\(profilePhotoUrlListOriginal)\n\n")

        let jsonString = profilePhotoUrlListOriginal.toJsonString()
        print("JSON string from dictionary: \n\(jsonString)\n\n")

        let profilePhotoUrlListRegenerated = ProfilePhotoUrlList(json:jsonString)
        print("Object from json string: \n\(profilePhotoUrlListRegenerated)\n\n")

        if profilePhotoUrlListOriginal == profilePhotoUrlListRegenerated {
            XCTAssert(true, "Success")
        } else {
            XCTAssert(false, "Faileure")
        }
    }

}

class Base: EVObject {
    var resource_uri: String?

    func getResourceId() -> String! {
        return resource_uri?.componentsSeparatedByString("/").last
    }
}

class Meta : EVObject {
    var limit : Int = 0
    var next : String?
    var offset : Int = 0
    var previous : String?
    var total_count : Int = 0
}

class ProfilePhotoUrl : Base {
    var url : String?
    var index : Int = 0
    var user : String?
    var id : Int = 0
}

class ProfilePhotoUrlList : EVObject {
    var meta: Meta?
    var objects: [ProfilePhotoUrl]?
}

JSON nested arrays not mapping correctly

I just downloaded the most recent project and added these three lines to EVReflectionJsonTests.swift
var test = userOriginal.company
var test2 = userOriginal.friends
var test3 = userOriginal.friends.first?.name

line 1 returns incorrect values for name/address (e.g. "\x88a\xc4\xba\xde\x7f")
line 2 returns an empty object (([EVReflectionTests.User]) test2 = {})
line 3 crashes the application

Nothing else was modified.

Avoid unused properties from JSON without warning

For now EVReflection is trying to convert every property from json object to swift class. If some property isn't defined in swift class that exist in json then EVReflection prints warning

The class 'ClassName' is not key value coding-compliant for the key 'PropertyName'
There is no support for optional type, array of optionals or enum properties.
As a workaround you can implement the function 'setValue forUndefinedKey' for this. See the unit tests for more

It would be nice if we have some solution for this problem more comfortable than override func setValue(value: AnyObject!, forUndefinedKey key: String) where we have to define all properties that we want to avoid. In case when there is a lot of them it is not comfortable.

I suggest to add method like:
func avoidMappingUndefinedProperties -> Bool
Default it could return false but we can have ability to override this method.

Type issue with propertyConverters()

class y : EVObject {
    var id = "y id"
}

class z: EVObject {
    var foo: String? = "foo"
    var bar: String? = "bar"
    var arr: [y] = []

    override func propertyConverters() -> [(String?, (Any?) -> (), () -> Any?)] {
        return [
            ( "arr",
                { self.arr = $0 as! [y] },
                { return self.arr.map({$0.id}) }
            )
        ]
    }  
}

let json = "{\"foo\": \"foobar\", \"arr\": [{\"id\": \"test\"}, {\"id\": \"test2\"}]}"
let r = z(json: json)

The above fails I think because the propertyConverter getter here returns a different type from the setter (this is the case where I want to output id's for subobjects when serializing to JSON but want to read full subobjects when deserializing from JSON).

I think the fix is this patch below -- basically, ignore the type from propertyConverter. However, I'm not sure if it's correct:

diff --git a/EVReflection/pod/EVReflection.swift b/EVReflection/pod/EVReflection.swift
index e2fc6d0..ff06139 100644
--- a/EVReflection/pod/EVReflection.swift
+++ b/EVReflection/pod/EVReflection.swift
@@ -852,12 +855,15 @@ final public class EVReflection {
                 }
                 if !skipThisKey {
                     var value = property.value
+                    // Convert the Any value to a NSObject value
+                    var (unboxedValue, valueType, isObject) = valueForAny(theObject, key: originalKey, anyValue: value)
+
                     // If there is a properyConverter, then use the result of that instead.
                     if let (_, _, propertyGetter) = (theObject as? EVObject)?.propertyConverters().filter({$0.0 == originalKey}).first {
                         value = propertyGetter()
+                        // Convert the Any value to a NSObject value but use original type.
+                        (unboxedValue, _, isObject) = valueForAny(theObject, key: originalKey, anyValue: value)
                     }
-                    // Convert the Any value to a NSObject value
-                    var (unboxedValue, valueType, isObject) = valueForAny(theObject, key: originalKey, anyValue: value)
                     if isObject {
                         // sub objects will be added as a dictionary itself.
                         let (dict, _) = toDictionary(unboxedValue as! NSObject, performKeyCleanup: performKeyCleanup)

Parsing XML with optional attributes causes crash

I have an XML document which contains an array of File objects where the format may or may not have the fps attribute.

    <file>
       <name>test.mp4</name>
       <format>MP4</format>
    </file>
    <file>
       <name>test.mp4</name>
       <format fps="30">MP4</format>
    </file>

The sample classes are:

class FormatTest : EVObject {
    var _fps = ""
    var __text = ""
}

class FileTest : EVObject {
    var name = ""
    var format = FormatTest()
}

When this gets converted to the FileTest object, it puts a String where the format object is, and causes a crash when you access the object.

From lldb:

(lldb) po obj.format
MP4

(lldb) po obj.format.dynamicType
__NSCFString

(lldb) po obj.format.__text
error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=1, address=0x0).
The process has been returned to the state before expression evaluation.

I think the problem is with EVReflection, and it should check the type of the property before storing it. If the property is a string and the property is an EVObject it should create that object and pass the string in as the __text attribute.

I'll fix the issue if you haven't gotten to it, or don't know about this one.

Sub-object properties

Hi,

I am having a little issue. I have a JSON file like this:

{ "Data": { "Name": "1", "ID": 2 } "Meta": "A class" }

I then have a class:

public class Foo { var Name: String var ID: Int var Meta: String }

How do I match Name to Data.Name?

I have tried the followings and can't make it work:

public class Foo { public class Data { var Name: String var ID: Int } var Meta: String }

and

override public func propertyMapping() -> [(String?, String?)] { return [("Name","Data.Name")] }

When set value from a int to a string, it will crash.

When the type from string to the object is mismatch, it will crash. For example, It's int type in the string and string type in the object. I think it should not crash in any situation, it could throw a exception.

Ignore properties with `nil` values on export only

We're trying to ignore all properties that have nil values on export only. However, we've found this isn't currently possible to do:

EVReflection currently offers two methods you can override to custom serialization/deserialization behavior: propertyMapping and propertyConverters.

By overriding propertyMapping, you can ignore a property by returning a tuple with a nil value (e.g. ("name", nil)), but AFAIK, it's not possible to do this only for export. That is, there's no indicator when this method is called (parameter or otherwise) that an export/import is happening.

By overriding propertyConverters, you can return a custom deserializer that returns nil, but this doesn't have the desired effect either: instead of ignoring the key/value in the JSON, the key is set as null.

We're happy to contribute a PR that will make it possible to ignore nil values on export/import only, but we wanted to make sure we ran this by you first to determine the desired way to do this.

Here are the options we've come up with:

  1. Allow nil serializer and deserializer returned from propertyConverters. If a nil serializer/deserializer is received, assume this means the property serialization/deserialization should be skipped.

This is our recommendation.

  1. Remove final from toDictionary and toJsonString on EVObject.

This is likely the easiest way forward, as we'd then have free control to override these and sanitize as we'd like. However, this feels like a "brute-force" way to do this.

  1. Change propertyMapping signature to provide an importing boolean or possibly enum to indicate whether importing/exporting is happening.

This was our first idea, but unfortunately, this method is used often throughout EVReflection, so the change (if possible) may be invasive. Also, we're not sure how to do this in a backwards-compatible manner yet.

Regardless of which route you'd like, we're happy to implement it and add unit tests. We just want to make sure we can get it into master.

@evermeer Which would you like to do?

Optional Int does not get set from dictionary or json string

Hi,

Optional Integers are not being set when initializing from dictionary or json string. I'm using EVReflection v2.18.0.

Here's an example:

class MyUser: EVObject {
    var id: Int?
    var firstName: String?
    var lastName: String?
}
var userDict = [
    "id": 1,
    "firstName": "First",
    "lastName": "Last"
]
var mu = MyUser(dictionary: userDict)
XCTAssertEqual(mu.toDictionary(), userDict)

outputs:

[... testCreatesUserFromDictionary] : XCTAssertEqual failed: ("Optional({
    id = "<null>";
    firstName = First;
    lastName = Last;
})") is not equal to ("Optional({
    id = 1;
    firstName = First;
    lastName = Last;
})") - 

And same goes for MyUser(json: "{\"id\":1,\"firstName\":\"First\",\"lastName\":\"Last\"}")

This is unexpected behavior, right?

It does work when I setup my class like the example:

class MyUser: EVObject {
    var id: Int = 0
    var firstName: String?
    var lastName: String?
}

Thanks

EVReflection handling of members which are generics

I know that generics needs to be handled special way.

However, workaround only shows how to handle when the whole object (which is serialized/deserialized is Generic).

It's not clear what to do when a member is of such generic class

Following code will fail

public class MyGenericBase: EVObject {
    var test : String = ""
}

public class InstanceObject: EVObject {
    var name:String?
}   

public class MyGenericObject<T where T:NSObject>: MyGenericBase, EVGenericsKVC {
    var data: T = T()
    var array: [T] = [T]()

    required public init() {
        super.init()
    }

    public override func setValue(value: AnyObject!, forUndefinedKey key: String) {
        switch key {
        case "data":
            data = value as! T
        case "array":
            array = value as! [T]
        default:
            print("---> setValue '\(value)' for key '\(key)' should be handled.")
        }
    }
}

class Foo {
   var bar : MyGenericObject<InstanceObject> = MyGenericObject<InstanceObject>()
}

var foo = Foo()
foo.bar.data.name = "Test"

var json = foo.toJsonString()
var foo2 = Foo(json: json) // This will fail

The reason for a failure is swiftClassTypeFromString. NSClassFromString returns nil for Generic type.

Two questions:

  1. Am I missing another workaround to handle this situation
  2. Is it possible to do automatical handling for this case?

fatal error: Array index out of range

Hello,
I'm using EVReflection (2.13.2) in xcode 7.2 and getting this error.

The error occurs when I'm have 2 objects with
var rows: [Row] = []
But this objects have an number different of itens in this array.

Works
{"containers": [{ "rows": [{"kind": "main"}, {"kind": "main"}] }, { "rows": [{"kind": "main"}, {"kind": "main"}] }] }

Crash:
{"containers": [{ "rows": [{"kind": "main"}, {"kind": "main"}] }, { "rows": [{"kind": "main"}, {"kind": "main"}, {"kind": "main"}] }] }

screen shot 2016-02-18 at 14 43 28

If Product Module Name is set in Build Settings, swiftClassTypeFromString() fails

swiftClassTypeFromString() calls getCleanAppName() to create the class string name; the problem is that the class name is in the form:

product_module_name.class_name

not

app_name.class_name

In my app at least. This causes swiftClassTypeFromString() to return nil and deserialization to fail.

I resolved it by adding

        if let klass = NSClassFromString(className) {
            return klass
        }

before the end of the swiftClassTypeFromString() function. But I wonder if the correct solution is to update getCleanAppName()?

Note that my object is flagged with
@objc(MyClassName) so that NSClassFromString works directly.

Swift ambiguity - JSONModel toDictionary vs EVReflection toDictionary

Thank you for investing a lot of time and effort, taking care and brining object mapping without head aches to Swift but...

So I have an old project in which I'm using models from Obj-C which of course inherit from JSONModel and because now I'm trying to slowly migrate everything to Swift, I'm trying EVReflection, but.......

As you already probably guessed, EVReflection is using the commodity of extending a base class which messes everything up. Instead of providing functionality only through its EVObject it extends directly the most core object Cocoa had from the Obj C times - NSObject. More specifically it has provided the "toDictionary" method in the extension to NSObject, which clearly conflicts with objects which inherited "toDictionary" method from JSONModel. [For testing: 1) make an obj c JSONModel subclass 2) in a Swift project where you're already using EVReflection try to use this JSONModel subclass instance\s method "toDictionary"]

And I do not import EVReflection in the file where I need the JSONModel functionality, but the compiler really doesn't care about this aspect.

I did some dirty fixes, like making a category in obj c which provides a wrapper method for the JSONModel toDictionary... but I suppose a lot of more hidden stones may appear in the future.

Can you please rethink your decision to extend NSObject and make everything available only through EVObject? or maybe provide a nice solution for not creating this kind of ugly intersections which may appear in the future also against other frameworks?

How to support custom defined enum

EVObject is strong enough to support custom defined class, but I can't find a way to support the custom defined enum. Is there a way to do that?

Swift 2.0 Support

There are a few try/catch refactors needed and removal of redundant superclasses from EVObject.

toJsonString() for Array

I need to convert an object array to JSON to save to a cache file.
Is there any way to do this with EVReflection?
I ended up adding this extension, which works. Just curious if it's necessary, or I'm missing something. Or if you'd like to add to EVReflection:

public extension Array {

    ///Convert this array to a json string
    public func toJsonString(performKeyCleanup:Bool = false) -> String {
        var jsonString = "[\n"
        for (index, item) in self.enumerate() {
            if let item = item as? NSObject {
                jsonString += EVReflection.toJsonString(item, performKeyCleanup: performKeyCleanup)
                if index < (self.count - 1) {
                    jsonString += ", \n"
                }
            }
        }
        jsonString += "\n]"

        return jsonString
    }
}

Dictionaries broken?

I really love EVReflection. But while testing the library i discovered a major problem for me.
I would like to get this result:

{
    "dict": {
        "foo": "bar"
    }
}

and used this code in the playground

import UIKit
import EVReflection

class User : EVObject {
    var dict : [String:String] = ["t":"bar"]
    required init() {
    }
}

let json = User().toJsonString()

But all i get is this uncaught exception:

2016-03-05 10:34:08.599 MyPlayground[51394:2089709] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<_TtGCSs29_NativeDictionaryStorageOwnerSSSS_ 0x7fc0a36022d0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key foo.'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000107863e65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x0000000109133deb objc_exception_throw + 48
    2   CoreFoundation                      0x0000000107863aa9 -[NSException raise] + 9
    3   Foundation                          0x00000001072e69bb -[NSObject(NSKeyValueCoding) setValue:forKey:] + 288
    4   EVReflection                        0x0000000115e8a7fe _TZFC12EVReflection12EVReflectionP33_B5E655244C8CE8B4EE02BAF482E9510D37convertDictionaryForJsonSerializationfMS0_FCSo12NSDictionaryS1_ + 398
    5   EVReflection                        0x0000000115e9943d _TZFC12EVReflection12EVReflectionP33_B5E655244C8CE8B4EE02BAF482E9510D32convertValueForJsonSerializationfMS0_FPSs9AnyObject_PS1__ + 1533
    6   EVReflection                        0x0000000115e8a762 _TZFC12EVReflection12EVReflectionP33_B5E655244C8CE8B4EE02BAF482E9510D37convertDictionaryForJsonSerializationfMS0_FCSo12NSDictionaryS1_ + 242
    7   EVReflection                        0x0000000115e8a380 _TZFC12EVReflection12EVReflection12toJsonStringfMS0_FTCSo8NSObject17performKeyCleanupSb_SS + 240
    8   EVReflection                        0x0000000115e79487 _TFC12EVReflection8EVObject12toJsonStringfS0_FTSb_SS + 71
    9   ???                                 0x00000001129050c7 0x0 + 4606415047
    10  MyPlayground                        0x00000001071b1840 main + 0
    11  MyPlayground                        0x00000001071b4711 _TTRXFo__dT__XFo_iT__iT__ + 17
    12  MyPlayground                        0x00000001071b41a1 _TPA__TTRXFo__dT__XFo_iT__iT__ + 81
    13  MyPlayground                        0x00000001071b4740 _TTRXFo_iT__iT__XFo__dT__ + 32
    14  MyPlayground                        0x00000001071b4777 _TTRXFo__dT__XFdCb__dT__ + 39
    15  CoreFoundation                      0x000000010778fa1c __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    16  CoreFoundation                      0x00000001077856a5 __CFRunLoopDoBlocks + 341
    17  CoreFoundation                      0x0000000107784e02 __CFRunLoopRun + 850
    18  CoreFoundation                      0x0000000107784828 CFRunLoopRunSpecific + 488
    19  GraphicsServices                    0x000000010e265ad2 GSEventRunModal + 161
    20  UIKit                               0x0000000107c10610 UIApplicationMain + 171
    21  MyPlayground                        0x00000001071b1d8a main + 1354
    22  libdyld.dylib                       0x000000010a98f92d start + 1
    23  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Am i missing something here?

Classes with EVObject attributes from another frameworks

Hi,

I think I found a bug and maybe I found a workaround. I am working with EVObjects in a framework. And I noticed that this attributes when constructed an object from a dictionary where always nil or an empty array.

I found out that the method

func valueForAny(parentObject:Any? = nil, key:String? = nil, anyValue: Any) -> (AnyObject, String)

was returning only the types name, for example Class, and not Framework.Class, the namespace prefix was not present.

I fixed it changing the line 446 of file EVReflection.swift from:

var subtype: String = "\(mi)"

to:

var subtype: String = String(reflecting: mi.subjectType)

Hope it helps

Use NSUTF8StringEncoding in toJSONString

Converting a string with foreign characters to a JSON string and then using that JSON string to construct the object back fails.

EVReflection.toJsonString should use NSUTF8StringEncoding instead of NSASCIIStringEncoding

    public class func toJsonString(theObject: NSObject) -> String {
        var toNSDict = EVReflection.toNSDictionary(theObject)
        var error:NSError? = nil
        if var jsonData = NSJSONSerialization.dataWithJSONObject(toNSDict , options: .PrettyPrinted, error: &error) {
            if var jsonString = NSString(data:jsonData, encoding:NSASCIIStringEncoding) {
                return jsonString as String
            }
        }
        return ""
    }

Inconsistent conversion NSNumber/String

I've observed the following issue. If i have a field of type NSNumber and within the json this field has a String value the conversion works (which is odd). On the other hand if i have a field of type String and within the json this field has a numeric value the app crashes with the following message: [__NSCFNumber length]: unrecognized selector sent to instance. In my opinion in both cases the conversion should just be skipped and a warning should be logged. I hope i could descripe the issue well enough. If you need more information just ask.

Nested types lead to problems in obtaining the class name

I put in Student class nested inside the Person class, and then get Student instance's class name, problems come:

class Person: EVObject {
      class Student: EVObject {
      }
}

then,

let classString = EVReflection.swiftStringFromClass(Person.Student())
println(classString)

Print result is: _TtCC4test6Person7Student

I think the class name results can be encapsulated into an object, such as the object of ordinary class name string, a class name string that contains the namespace, which is more flexible

let classStringObj: ClassString = EVReflection.swiftStringFromClass(Person.Student())

classStringObj.shortString //return "Student"

classStringObj.fullString //return "Person.Student"

thank you!

Issue with using Array<CustomClass> in Custom Class

The following does not work properly

class MyOtherClass {
var id: Int = 0
}

class MyClass {
var id: Int = 0
var list = Array()
}

json = {"id": 10, "list": [{"id": 10}]}
MyClass(json: json) -> Return MyClass with only id and list is an empty array.

In looking at the code, it seem the issue is with this method implementation: dictionaryAndArrayConversion in EVReflection.swift

Thanks,

init() issue

hi I have a question:

i have this class:

public class ResponseLogin: Response {
    var token:String
    var sessionId:String
    var codFiscale:String

    var nome:String
    var cognome:String


    init(token: String, sessionId: String, codFiscale: String, nome: String, cognome : String, statusCode: String, elencoMessaggi: [Messaggio]) {

        self.token = token
        self.sessionId = sessionId
        self.codFiscale = codFiscale
        self.nome = nome
        self.cognome = cognome

        super.init(statusCode: statusCode, elencoMessaggi: elencoMessaggi)
    }
}

when i call the class

  let responseObj:ResponseLogin = ResponseLogin(json: data)

it required me all the parameters and json:data it considered an extra.

what is the best practise?

Suggestion on use of reserved words handling

Hi there,

Firstly, your code has been a great help in the project I'm working on and has saved me a lot of typing! So thank you for that :)

Just a suggestion to improve things the handling of reserved words - I've just had a put in a bit of a hack to handle the conversion back of _as and _is. Shouldn't the underscore be removed when converting an NSObject back into a JSON string. The API I'm using makes use of as and is as keys (don't ask!) and they map happily to _as and _is on the JSON->object but not going back the other way.

Thanks again.

Best wishes,

Gareth.

failable initializers

Since swift support failable initializers, we can use it in our project. For example, if we pass a invalid json string to the initializer, we can return nil value.

performKeyCleanup not working with class attributes of type EVObject

In this example:

class User: EVObject {
    var id: Int = 0
    var name: String = ""
    var closeFriends: [User]? = []
}

var user = User()
...
var dic = user.toDictionary(true)

I got in the dictionary the key "close_friends", but when I inspect the value of dic["close_friends"][0], it has the key "closeFriends" and not "close_friends"

I Got AN ERROR WITH this JSON String!Help!!

{
"status" : 0,
"data" : [
{
"PriceCount" : "8.50",
"Remark" : "",
"OrderId" : "",
"GoodsList" : [
{
"Unit" : "斤",
"BuyCount" : 1,
"GoodsPic" : "",
"GoodsName" : "",
"BuyPrice" : 8.5,
"GoodsDetail" : "口感",
"GoodsId" : "6a4ee4ae-c1f3-4ba2-a267-04f5e193dd85",
"OriginalPrice" : 9,
"Describe" : "新鲜"
}
]
},
{
"PriceCount" : "8.50",
"Remark" : "",
"OrderId" : "20160330112023670746",
"GoodsList" : [
{
"Unit" : "斤",
"BuyCount" : 1,
"GoodsPic" : "http://103.21.118.204:8070//UploadFiles/GoodsImage/20160310103712.png",
"GoodsName" : "黄金帅苹果",
"BuyPrice" : 8.5,
"GoodsDetail" : "口感新鲜",
"GoodsId" : "6a4ee4ae-c1f3-4ba2-a267-04f5e193dd85",
"OriginalPrice" : 9,
"Describe" : "新鲜"
}
]
},
{
"PriceCount" : "8.50",
"Remark" : "",
"OrderId" : "20160329175029050163",
"GoodsList" : [
{
"Unit" : "斤",
"BuyCount" : 1,
"GoodsPic" : "http://103.21.118.204:8070//UploadFiles/GoodsImage/20160310103712.png",
"GoodsName" : "黄金帅苹果",
"BuyPrice" : 8.5,
"GoodsDetail" : "口感新鲜",
"GoodsId" : "6a4ee4ae-c1f3-4ba2-a267-04f5e193dd85",
"OriginalPrice" : 9,
"Describe" : "新鲜"
}
]
},
{
"PriceCount" : "8.50",
"Remark" : "",
"OrderId" : "20160329112553781815",
"GoodsList" : [
{
"Unit" : "斤",
"BuyCount" : 1,
"GoodsPic" : "http://103.21.118.204:8070//UploadFiles/GoodsImage/20160310103712.png",
"GoodsName" : "黄金帅苹果",
"BuyPrice" : 8.5,
"GoodsDetail" : "口感新鲜",
"GoodsId" : "6a4ee4ae-c1f3-4ba2-a267-04f5e193dd85",
"OriginalPrice" : 9,
"Describe" : "新鲜"
}
]
},
{
"PriceCount" : "8.50",
"Remark" : "",
"OrderId" : "20160328160717612823",
"GoodsList" : [
{
"Unit" : "斤",
"BuyCount" : 1,
"GoodsPic" : "http://103.21.118.204:8070//UploadFiles/GoodsImage/20160310103712.png",
"GoodsName" : "黄金帅苹果",
"BuyPrice" : 8.5,
"GoodsDetail" : "口感新鲜",
"GoodsId" : "6a4ee4ae-c1f3-4ba2-a267-04f5e193dd85",
"OriginalPrice" : 9,
"Describe" : "新鲜"
}
]
},
{
"PriceCount" : "28.80",
"Remark" : "",
"OrderId" : "20160328152442225583",
"GoodsList" : [
{
"Unit" : "份",
"BuyCount" : 1,
"GoodsPic" : "http://103.21.118.204:8070//UploadFiles/GoodsImage/20160315041215.png",
"GoodsName" : "新鲜鸡蛋(散装)30枚 约2kg/份",
"BuyPrice" : 28.8,
"GoodsDetail" : "新鲜健康",
"GoodsId" : "3c0bc1a1-86e9-46d5-a379-d3e225148fc4",
"OriginalPrice" : 29,
"Describe" : "新鲜"
}
]
},
{
"PriceCount" : "4560.00",
"Remark" : "",
"OrderId" : "20160328101203382586",
"GoodsList" : [
{
"Unit" : "瓶",
"BuyCount" : 38,
"GoodsPic" : "http://103.21.118.204:8070//UploadFiles/GoodsImage/20160315040019.png",
"GoodsName" : "金龙鱼花生油5L",
"BuyPrice" : 120,
"GoodsDetail" : "健康油,喝好油",
"GoodsId" : "b062cd0d-dca2-4bf0-bae9-4352071e39f6",
"OriginalPrice" : 125,
"Describe" : "非转基因;5S压榨"
}
]
},
{
"PriceCount" : "17.00",
"Remark" : "",
"OrderId" : "20160328101157282871",
"GoodsList" : [
{
"Unit" : "斤",
"BuyCount" : 2,
"GoodsPic" : "http://103.21.118.204:8070//UploadFiles/GoodsImage/20160310103712.png",
"GoodsName" : "黄金帅苹果",
"BuyPrice" : 8.5,
"GoodsDetail" : "口感新鲜",
"GoodsId" : "6a4ee4ae-c1f3-4ba2-a267-04f5e193dd85",
"OriginalPrice" : 9,
"Describe" : "新鲜"
}
]
},
{
"PriceCount" : "5012.00",
"Remark" : "",
"OrderId" : "20160328101150569734",
"GoodsList" : [
{
"Unit" : "斤",
"BuyCount" : 179,
"GoodsPic" : "http://103.21.118.204:8070//UploadFiles/GoodsImage/20160310103913.png",
"GoodsName" : "**阿克苏冰糖心苹果",
"BuyPrice" : 28,
"GoodsDetail" : "产自**,味道可口",
"GoodsId" : "01e65a03-2115-4852-9f1f-363b7dcf06b6",
"OriginalPrice" : 30,
"Describe" : "新鲜"
}
]
},
{
"PriceCount" : "45.60",
"Remark" : "",
"OrderId" : "20160325115107019274",
"GoodsList" : [

  ]
}

],
"msg" : "获取成功",
"total" : 12
}

fatal error: NSArray element failed to match the Swift Array Element type
Printing description of mi.displayStyle:
▿ Optional

  • Some : Swift.Mirror.DisplayStyle.Optional

The third EVObject Get ThisError

func swiftClassTypeFromString(className: String) -> AnyClass! return nil

public class func swiftClassTypeFromString(className: String) -> AnyClass! {

// if className.hasPrefix("Optional<") {
// className = className.substringWithRange(Range<String.Index>(start: className.startIndex.advancedBy(9), end: className.endIndex.advancedBy(-1)))
// }
if className.hasPrefix("_TtC") {
return NSClassFromString(className)
}
var classStringName = className
if className.rangeOfString(".", options: NSStringCompareOptions.CaseInsensitiveSearch) == nil {
let appName = getCleanAppName()
classStringName = "(appName).(className)"
}
return NSClassFromString(classStringName)
}

(lldb) po NSClassFromString("麦田.ImageTextContent")
nil

var appName = bundle.infoDictionary?["CFBundleName"] as? String ?? ""
appName is "麦田"

EVReflection valueForAny fails with long number

At the bottom of this function there is the following switch statement:

...
switch(theValue){
case let longValue as Int64:
return (NSNumber(long: CLong(longValue)), "NSNumber")
case let intValue as Int:
return (NSNumber(Int: CInt(intValue)),"NSNumber")
...

If theValue is typed as NSNumber with a high value e.g 458347978508 then the second case is selected instead of the first one. This leads to a EXC_BAD_INSTRUCTION.

I think the problem is that the value fits into an Int within a 64 Bit enviorment but not into a CInt. However i'm not sure why the first case is skipped.

I think maybe it should be like this:

...
switch(theValue){
case let longValue as Int64:
return (NSNumber(long: CLongLong(longValue)), "NSNumber")
case let intValue as Int:
return (NSNumber(Int: CLong(intValue)),"NSNumber")
...

CLong is actually a typealias for Int and CLongLong is a typealias for Int64.

EV doesn't parse subtypes if bundle name is changed manually

In a project, I set the Bundle name manually to sth else, such as "firstresponder" instead of $(PRODUCT_NAME). I also have the following two classes:
Foo {
var f1: String
var boo: Boo
}

Boo {
var ***
}

When i parse a json to Foo with : Foo(json: data), the Foo.boo is always empty. So I stepped through the json function and then found out that the "NSClassFromString(classStringName)" is always nil because it canno't find class firstresponder.Boo. After I changed the bundle name back to $(PRODUCT_NAME), it works!

I didn't read through the getCleanAppName and I'm new to iOS, but I'm just wondering if it should read the project target instead of the bundle name because I think project target is where you can reference the classes.

Thanks and Cheers!

Memory Leak?

Hi I am using version 2.20.2. There appears to be a memory leak when converting to and from JSON, more so when converting from JSON to an object.

My JSON has more values and levels but I was able to reproduce it with a simpiler structure.

{
    "name" : "Test",
    "listOfObjects" : [
        {
            "name" : "Object 1",
            "value" : "Value 1"   
        }
    ]
}

Create about 8000 of the list objects, and try and convert to JSON. You will see a spike of memory. Try to convert the JSON back to objects and you will see a big spike in memory.

If you profile in instruments you will see the JSON lines of code come up with memory leak warning. A very quick look at the allocations and it seams like there are a few items in side of EVReflect that are probably causing most of the issues. I haven't gotten a chance to dig in to the code and see if I can figure out where exactly it's coming from. If I get a chance to look into it more I will let you know.

EVReflection does ignoring too late (and goes into an infinite loop)

Objects may have circular references:

class Foo : EVObject {
var bars : Bar[]
}

class Bar : EVObject {
var foo : Foo

// Let's ignore foo
override func propertyMapping() -> [(String?, String?)] {
return [("foo",nil)]
}
}

If we will attempt to serialize this to json, it will get into an infinite recursion loop while consruction a dictionary.

PropertyMapping is done later in the game (when the dictionary is constructed) and won't prevent this infinite loop.

EVReflection parse to array issue Swift 2.0?

In my podfile: use_frameworks! pod 'EVReflection', '~> 2.6'

Added a class:

public class SubscriptionsItem: EVObject {
    var subscriptionId: String = ""
    var title: String = ""
    var count: Int = 0
}

Now i'm trying to parse json data to my array of SubscriptionsItems:
subscriptionEntries = [SubscriptionsItem](json: responseObject)

I'm getting 'Cannot invoke initiallizer for type '[SubscriptionsItem]' with an argument list of type '(json: String)'.

Can't figure out what i'm doing wrong here?

Not Support the array optional

which mean, support code here:

class User: EVObject {
    var id: Int = 0
    var name: String = ""
    var email: String?
    var company: Company?
    var friends: [User] = []
}

class Company: EVObject {
    var name: String = ""
    var address: String?
}

not support code here

class User: EVObject {
    var id: Int = 0
    var name: String = ""
    var email: String?
    var company: Company?
    var friends: [User]? = []
}

class Company: EVObject {
    var name: String = ""
    var address: String?
}

framework not found EVReflection

Mac OSX 10.11.1
Xcode 7.1

I installed the library following this steps:

Open Terminal and execute: $ sudo gem install cocoapods
Navigate to my Project folder (example /Users/myName/Documents/APP/APP.xcodeproj).
Setup Cocoapod: pod setup
Create the Podfile: touch Podfile
Open the Podfile: open -e Podfile
Insert code for Podfile:
use_frameworks!
pod "EVReflection", '~> 2.6'
Finally install the Podfile pod install

when I run the app I receive this error:
ld: framework not found EVReflection
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Very Slow Performance Parsing Json

Hello,
I'm testing speed of json libraries and have big problems with EVReflection.

The EVReflection parse is taking 42 SECONDS to parse this model and this json with recursive objects in lists. Running in the simulator. In the device it crash, out of memory!

Do you think we can change this or it is a real problem of evereflection and we need to migrate to faster libs? I can help to fix if you have some tips about where can be the problem.

Thank you

Model:
`import UIKit
import EVReflection

class SpeedReflection: EVObject {
var name: String? = nil
var list: [SpeedReflection]? = nil
}`

JSON:
{ "name": "String Long Name", "list": [{ "name": "String Long Name", "list": [{ "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }] }, { "name": "String Long Name", "list": [{ "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [{ "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }] }, { "name": "String Long Name", "list": [{ "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [{ "name": "String Long Name", "list": [{ "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [{ "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [{ "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [{ "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [{ "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }] }, { "name": "String Long Name", "list": [] }] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }] }] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [{ "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }, { "name": "String Long Name", "list": [] }] }] }

Mapping names from snake case JSON to camel case Object

Hi again,

I am working with a json in snake case and classes in camel case. I found that some atributes in my class were not set.

To correct this I changed the line 60 of file EVReflection.swift

from:

if let dictValue = dictionaryAndArrayConversion(types[k as! String], original: original, dictValue: v) {

to:

if let dictValue = dictionaryAndArrayConversion(types[mapping ?? k as! String], original: original, dictValue: v) {

It solved my problem.

Hope it helps

Nested Object convert failed

hi, i'm using the master version with xcode7 & swift2.0, and my objects like this:
class Comment: EVObject {
var commentid = ""
var content = ""
var ctime = ""
var status = "2"
var img = ""
var vote = "0"
var userinfo : UserInfo?
}

class UserInfo: EVObject{
var avatar = ""
var uid = ""
var telnum = ""
var is_seller = "0"
var sex = "M"
var name = "TestUser"
var interest = ""
}

then i use the code like this

var test = "[{"status":"0","content":"goodjob","ctime":"1439986013","img":"","userinfo":{"avatar":"/5602503cc79de.jpg","uid":"88ffab2d738393fa467a2e98cad855d9","telnum":"18520284321","sex":"M","name":"","interest":""},"commentid":"18", "vote" : "0"}]"
var comments = EVReflection.arrayFromJson(Comment(), json: test)
print(comments[0].userinfo.uid)

error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
The process has been returned to the state before expression evaluation.

got "fatal error: NSArray element failed to match the Swift Array Element type"

I really love EVReflection. It reminds me of the happy time with C#.

But I found under below circumstance, EVReflection will got error ""fatal error: NSArray element failed to match the Swift Array Element type".

Class definition(put them in a different file from ut!):

public class A : EVObject{
    public var bs : [B] = []
}

public class B : EVObject{
    public var val : Int = 0
}

ut:

    func testJSONArray(){
        let a = A()
        let b = B()
        b.val = 1
        a.bs.append(b)
        a.bs.append(b)
        a.bs.append(b)
        a.bs.append(b)
        a.bs.append(b)
        a.bs.append(b)
        a.bs.append(b)
        let str = a.toJsonString()
        print(str)
        let a2 = A(json: str)
        print(a2.toJsonString())
    }

If I put the class definition in ut file, it works fine.But if I put the class definition in another file of the app target, it just went wrong.

EVReflection valueForAny unkown type _StringCore

I did update to 2.12.1 version and when I call to toJsonString() function the app is crashing. Previously. in 2.11.1 version, the code worked smoothly.

The classes that I'm trying to convert are the following:

import EVReflection

class BoundRequest:EVObject{
    var action:String = "byBounds"
    var platform:String = "android"
    var types:[String] = []
    var bounds:Bound = Bound()
}

class Bound:EVObject {
    var ne:Coordinate = Coordinate()
    var sw:Coordinate = Coordinate()    
}

class Coordinate:EVObject{
    var lat:Double=0
    var lng:Double=0

    func getCoordinate()->CLLocationCoordinate2D{
        return CLLocationCoordinate2D(latitude: lat, longitude: lng)
    }

    func setLatLng(lat:Double!,lng:Double!){
        self.lat=lat
        self.lng=lng
    }

    func setLatLng(latLng:CLLocationCoordinate2D){
        self.lat = latLng.latitude
        self.lng = latLng.longitude
    }
}

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.