Skip to content

Instantly share code, notes, and snippets.

@amirrajan
Created January 9, 2019 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amirrajan/89bde2e53f83ba0bcc308ea58245c250 to your computer and use it in GitHub Desktop.
Save amirrajan/89bde2e53f83ba0bcc308ea58245c250 to your computer and use it in GitHub Desktop.
JSON string to ruby hash using RubyMotion
# https://github.com/rubymotion/BubbleWrap/blob/master/motion/core/json.rb
# Handles JSON encoding and decoding in a similar way Ruby 1.9 does.
module JSON
class ParserError < StandardError; end
# Parses a string or data object and converts it in data structure.
#
# @param [String, NSData] str_data the string or data to serialize.
# @raise [ParserError] If the parsing of the passed string/data isn't valid.
# @return [Hash, Array, NilClass] the converted data structure, nil if the incoming string isn't valid.
#
# TODO: support options like the C Ruby module does
def self.parse(str_data)
return nil unless str_data
data = str_data.respond_to?('dataUsingEncoding:') ? str_data.dataUsingEncoding(NSUTF8StringEncoding) : str_data
opts = NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves | NSJSONReadingAllowFragments
error = Pointer.new(:id)
obj = NSJSONSerialization.JSONObjectWithData(data, options: opts, error: error)
raise ParserError, error[0].description if error[0]
if block_given?
yield obj
else
obj
end
end
def self.generate(obj)
NSJSONSerialization.dataWithJSONObject(obj, options: 0, error: nil).to_str
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment