KSON (j -> k)*

a JSON library

like GSON, but for Swift

*Very early proof of concept, subject to change completely

A Highlight Hackathon Project

This sucks

What if...

You could just define your class

You didn't have to do write any (de)serialization code

Introducing KSON

First make your models

Then initialize a KSON

Finally, make the object

Use the standard NSJSONSerialization Cocoa class to turn your JSON string into an NSDictionary

Wow this is really production ready after only one day?


But it works


How does it work?


More specifically:

  • Swift doesn't have proper reflection
  • Objective-C has a powerful runtime library
  • You can make Swift classes extend from NSObject

So isn't it easy?

No, it's complicated

  • Swift properties are not necessarily supported from within Objective-C,
    • Therefore, must use as much of Swift's read-only reflection as possible (and it's not powerful enough)
  • Writing to Swift properties involves breaking out of the managed memory land
    • Therefore, there are probably memory leaks
  • You can't ask an Any value or Any.Type if it's an Array<SuperClass> if it's really an Array<Subclass>
    • This means we have to use NSArray and the meta-type property associated with them
    • If anyone figures this out, let me know

TODO more implementation details


  • Must use NSArray and NSString
  • Memory may leak
    • But the leak instrument says there are no leaks
  • Performance
    • No time for benchmarks, but due to lots of Objective-C Swift jumps and reflection, it's likely slow
  • Only Array<String>, NSString, NSArray of JSON fully implemented
    • Proof of concept for primitive values
  • Code needs to be cleaned and API improved

It's GSON in Swift, that's awesome



For implementation, see github in the near future


By bkase


  • 2,360
Loading comments...

More from bkase