@@ -307,19 +307,30 @@ def generate(obj)
307307
308308 # Handles @allow_nan, @buffer_initial_length, other ivars must be the default value (see above)
309309 private def generate_json ( obj , buf )
310- case obj
311- when Hash
310+ klass = obj . class
311+ if klass == Hash
312312 buf << '{'
313313 first = true
314314 obj . each_pair do |k , v |
315315 buf << ',' unless first
316- fast_serialize_string ( k . to_s , buf )
316+
317+ key_str = k . to_s
318+ if key_str . is_a? ( ::String )
319+ if key_str . class == ::String
320+ fast_serialize_string ( key_str , buf )
321+ else
322+ generate_json ( key_str , buf )
323+ end
324+ else
325+ raise TypeError , "#{ k . class } #to_s returns an instance of #{ key_str . class } , expected a String"
326+ end
327+
317328 buf << ':'
318329 generate_json ( v , buf )
319330 first = false
320331 end
321332 buf << '}'
322- when Array
333+ elsif klass == Array
323334 buf << '['
324335 first = true
325336 obj . each do |e |
@@ -328,9 +339,9 @@ def generate(obj)
328339 first = false
329340 end
330341 buf << ']'
331- when String
342+ elsif klass == String
332343 fast_serialize_string ( obj , buf )
333- when Integer
344+ elsif klass == Integer
334345 buf << obj . to_s
335346 else
336347 # Note: Float is handled this way since Float#to_s is slow anyway
@@ -419,7 +430,15 @@ def json_transform(state)
419430 each { |key , value |
420431 result << delim unless first
421432 result << state . indent * depth if indent
422- result = +"#{ result } #{ key . to_s . to_json ( state ) } #{ state . space_before } :#{ state . space } "
433+
434+ key_str = key . to_s
435+ key_json = if key_str . is_a? ( ::String )
436+ key_str = key_str . to_json ( state )
437+ else
438+ raise TypeError , "#{ key . class } #to_s returns an instance of #{ key_str . class } , expected a String"
439+ end
440+
441+ result = +"#{ result } #{ key_json } #{ state . space_before } :#{ state . space } "
423442 if state . strict? && !( false == value || true == value || nil == value || String === value || Array === value || Hash === value || Integer === value || Float === value )
424443 raise GeneratorError , "#{ value . class } not allowed in JSON"
425444 elsif value . respond_to? ( :to_json )
0 commit comments