@@ -307,19 +307,30 @@ def generate(obj)
307
307
308
308
# Handles @allow_nan, @buffer_initial_length, other ivars must be the default value (see above)
309
309
private def generate_json ( obj , buf )
310
- case obj
311
- when Hash
310
+ klass = obj . class
311
+ if klass == Hash
312
312
buf << '{'
313
313
first = true
314
314
obj . each_pair do |k , v |
315
315
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
+
317
328
buf << ':'
318
329
generate_json ( v , buf )
319
330
first = false
320
331
end
321
332
buf << '}'
322
- when Array
333
+ elsif klass == Array
323
334
buf << '['
324
335
first = true
325
336
obj . each do |e |
@@ -328,9 +339,9 @@ def generate(obj)
328
339
first = false
329
340
end
330
341
buf << ']'
331
- when String
342
+ elsif klass == String
332
343
fast_serialize_string ( obj , buf )
333
- when Integer
344
+ elsif klass == Integer
334
345
buf << obj . to_s
335
346
else
336
347
# Note: Float is handled this way since Float#to_s is slow anyway
@@ -419,7 +430,15 @@ def json_transform(state)
419
430
each { |key , value |
420
431
result << delim unless first
421
432
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 } "
423
442
if state . strict? && !( false == value || true == value || nil == value || String === value || Array === value || Hash === value || Integer === value || Float === value )
424
443
raise GeneratorError , "#{ value . class } not allowed in JSON"
425
444
elsif value . respond_to? ( :to_json )
0 commit comments