Merge pull request #718 from djones6/json_dataperf

diff --git a/Foundation/NSJSONSerialization.swift b/Foundation/NSJSONSerialization.swift
index a012ec1..cd4aed7 100644
--- a/Foundation/NSJSONSerialization.swift
+++ b/Foundation/NSJSONSerialization.swift
@@ -101,14 +101,13 @@
     /* Generate JSON data from a Foundation object. If the object will not produce valid JSON then an exception will be thrown. Setting the NSJSONWritingPrettyPrinted option will generate JSON with whitespace designed to make the output more readable. If that option is not set, the most compact possible JSON will be generated. If an error occurs, the error parameter will be set and the return value will be nil. The resulting data is a encoded in UTF-8.
      */
     internal class func _data(withJSONObject value: Any, options opt: WritingOptions, stream: Bool) throws -> Data {
-        var result = Data()
+        var jsonStr = String()
         
         var writer = JSONWriter(
             pretty: opt.contains(.prettyPrinted),
             writer: { (str: String?) in
                 if let str = str {
-                    let count = str.lengthOfBytes(using: .utf8)
-                    result.append(UnsafeRawPointer(str.cString(using: .utf8)!).bindMemory(to: UInt8.self, capacity: count), count: count)
+                    jsonStr.append(str)
                 }
             }
         )
@@ -131,6 +130,14 @@
             }
         }
         
+        let count = jsonStr.lengthOfBytes(using: .utf8)
+        let bufferLength = count+1 // Allow space for null terminator
+        var utf8: [CChar] = Array<CChar>(repeating: 0, count: bufferLength)
+        if !jsonStr.getCString(&utf8, maxLength: bufferLength, encoding: .utf8) {
+            fatalError("Failed to generate a CString from a String")
+        }
+        let rawBytes = UnsafeRawPointer(UnsafePointer(utf8))
+        let result = Data(bytes: rawBytes.bindMemory(to: UInt8.self, capacity: count), count: count)
         return result
     }
     open class func data(withJSONObject value: Any, options opt: WritingOptions = []) throws -> Data {