Skip to content

Implementing JSONSerialization.writeJSONObject #465

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 26, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Foundation/NSJSONSerialization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,9 @@ public class JSONSerialization : NSObject {
/* Write JSON data into a stream. The stream should be opened and configured. The return value is the number of bytes written to the stream, or 0 on error. All other behavior of this method is the same as the dataWithJSONObject:options:error: method.
*/
public class func writeJSONObject(_ obj: AnyObject, toStream stream: NSOutputStream, options opt: WritingOptions) throws -> Int {
NSUnimplemented()
let jsonData = try data(withJSONObject: obj, options: opt)
let jsonNSData = jsonData.bridge()
return stream.write(UnsafeMutablePointer<UInt8>(jsonNSData.bytes), maxLength: jsonNSData.length)
}

/* Create a JSON object from JSON data stream. The stream should be opened and configured. All other behavior of this method is the same as the JSONObjectWithData:options:error: method.
Expand Down
97 changes: 97 additions & 0 deletions TestFoundation/TestNSJSONSerialization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,10 @@ extension TestNSJSONSerialization {
("test_serialize_stringEscaping", test_serialize_stringEscaping),
("test_serialize_invalid_json", test_serialize_invalid_json),
("test_jsonReadingOffTheEndOfBuffers", test_jsonReadingOffTheEndOfBuffers),
("test_jsonObjectToOutputStreamBuffer", test_jsonObjectToOutputStreamBuffer),
("test_jsonObjectToOutputStreamFile", test_jsonObjectToOutputStreamFile),
("test_invalidJsonObjectToStreamBuffer", test_invalidJsonObjectToStreamBuffer),
("test_jsonObjectToOutputStreamInsufficeintBuffer", test_jsonObjectToOutputStreamInsufficeintBuffer),
]
}

Expand Down Expand Up @@ -759,4 +763,97 @@ extension TestNSJSONSerialization {
XCTFail("Unknow json decoding failure")
}
}

func test_jsonObjectToOutputStreamBuffer(){
let dict = ["a":["b":1]]
do {
let buffer = Array<UInt8>(repeating: 0, count: 20)
let outputStream = NSOutputStream(toBuffer: UnsafeMutablePointer<UInt8>(buffer), capacity: 20)
outputStream.open()
let result = try JSONSerialization.writeJSONObject(dict.bridge(), toStream: outputStream, options: [])
outputStream.close()
if(result > -1) {
XCTAssertEqual(NSString(bytes: buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue), "{\"a\":{\"b\":1}}")
}
} catch {
XCTFail("Error thrown: \(error)")
}
}

func test_jsonObjectToOutputStreamFile() {
let dict = ["a":["b":1]]
do {
let filePath = createTestFile("TestFileOut.txt",_contents: Data(capacity: 128)!)
if filePath != nil {
let outputStream = NSOutputStream(toFileAtPath: filePath!, append: true)
outputStream?.open()
let result = try JSONSerialization.writeJSONObject(dict.bridge(), toStream: outputStream!, options: [])
outputStream?.close()
if(result > -1) {
let fileStream: InputStream = InputStream(fileAtPath: filePath!)!
var buffer = [UInt8](repeating: 0, count: 20)
fileStream.open()
if fileStream.hasBytesAvailable {
let resultRead: Int = fileStream.read(&buffer, maxLength: buffer.count)
fileStream.close()
if(resultRead > -1){
XCTAssertEqual(NSString(bytes: buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue), "{\"a\":{\"b\":1}}")
}
}
removeTestFile(filePath!)
} else {
XCTFail("Unable to create temp file")
}
}
} catch {
XCTFail("Error thrown: \(error)")
}
}

func test_jsonObjectToOutputStreamInsufficeintBuffer() {
let dict = ["a":["b":1]]
let buffer = Array<UInt8>(repeating: 0, count: 10)
let outputStream = NSOutputStream(toBuffer: UnsafeMutablePointer<UInt8>(buffer), capacity: 20)
outputStream.open()
do {
let result = try JSONSerialization.writeJSONObject(dict.bridge(), toStream: outputStream, options: [])
outputStream.close()
if(result > -1) {
XCTAssertNotEqual(NSString(bytes: buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue), "{\"a\":{\"b\":1}}")
}
} catch {
XCTFail("Error occurred while writing to stream")
}
}

func test_invalidJsonObjectToStreamBuffer() {
let str = "Invalid JSON"
let buffer = Array<UInt8>(repeating: 0, count: 10)
let outputStream = NSOutputStream(toBuffer: UnsafeMutablePointer<UInt8>(buffer), capacity: 20)
outputStream.open()
XCTAssertThrowsError(try JSONSerialization.writeJSONObject(str.bridge(), toStream: outputStream, options: []))
}

private func createTestFile(_ path: String,_contents: Data) -> String? {
let tempDir = "/tmp/TestFoundation_Playground_" + NSUUID().UUIDString + "/"
do {
try FileManager.default().createDirectory(atPath: tempDir, withIntermediateDirectories: false, attributes: nil)
if FileManager.default().createFile(atPath: tempDir + "/" + path, contents: _contents,
attributes: nil) {
return tempDir + path
} else {
return nil
}
} catch _ {
return nil
}
}

private func removeTestFile(_ location: String) {
do {
try FileManager.default().removeItem(atPath: location)
} catch _ {

}
}
}