Search code examples
iosjsonrubymotion

Error Parsing JSON in RubyMotion


I'm trying to parse the following JSON:

"{\"name\":\"Damien\",\"message\":[\"Hi\"]}"

However, I've tried native parsing and Bubblewrap only to get the following error:

-[__NSCFString bytes]: unrecognized selector sent to instance 0x98bde40 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString bytes]: unrecognized selector sent to instance 0x98bde40'

I've tried:

e = Pointer.new(:object)
json_hash = NSJSONSerialization.JSONObjectWithData(json_string, options:0, error: e)

and

json_hash = BW::JSON.parse(json_string)

Both yield the same error. What am I doing wrong?


Solution

  • `JSONObjectWithData:options:error:' requires NSData object instead of String. You can convert from String to NSData using String#to_data

    json_string = "{\"name\":\"Damien\",\"message\":[\"Hi\"]}"
    e = Pointer.new(:object)
    json_hash = NSJSONSerialization.JSONObjectWithData(json_string.to_data, options:0, error: e)