Search code examples
rubyrubymotion

using NSJSONSerialization in RubyMotion


I'm using RubyMotion and trying to serialize an object to json. I'm not getting an error message but this causes my app to crash.

  class Foo
     attr_accessor :name
  end

  e = Pointer.new(:object) 

  testItem = Foo.new              
  testItem.name = "test"          

  testJson = NSJSONSerialization.dataWithJSONObject(testItem, options:0, error: e)

Can anyone see if Im using this class correctly? (or know an alternative)


Solution

  • There is nothing wrong with your call. The problem is with your data. The top level object in your testItem must be an NSArray or an NSDictionary.

    You can use RubyMotion arrays and hashes since Array < NSMutableArray < NSArray and Hash < NSMutableDictionary < NSDictionary.

    Try these sample testItems with your call:

    testItem = ["test"]
    testItem = {"names" => ["Fred", "Joe", "Mike"], "ages" => [17, 63, 28]}
    

    From NSJSONSerialization.h:

    /* A class for converting JSON to Foundation objects and converting Foundation objects to JSON.
    
       An object that may be converted to JSON must have the following properties:
        - Top level object is an NSArray or NSDictionary
        - All objects are NSString, NSNumber, NSArray, NSDictionary, or NSNull
        - All dictionary keys are NSStrings
        - NSNumbers are not NaN or infinity
    */