Skip to content

Commit 2acafc7

Browse files
saiHemakparkera
authored andcommitted
Implementing JSONSerialization.writeJSONObject (#465)
1 parent 038d708 commit 2acafc7

File tree

2 files changed

+100
-1
lines changed

2 files changed

+100
-1
lines changed

Foundation/NSJSONSerialization.swift

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,9 @@ public class JSONSerialization : NSObject {
159159
/* 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.
160160
*/
161161
public class func writeJSONObject(_ obj: AnyObject, toStream stream: NSOutputStream, options opt: WritingOptions) throws -> Int {
162-
NSUnimplemented()
162+
let jsonData = try data(withJSONObject: obj, options: opt)
163+
let jsonNSData = jsonData.bridge()
164+
return stream.write(UnsafeMutablePointer<UInt8>(jsonNSData.bytes), maxLength: jsonNSData.length)
163165
}
164166

165167
/* 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.

TestFoundation/TestNSJSONSerialization.swift

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -585,6 +585,10 @@ extension TestNSJSONSerialization {
585585
("test_serialize_stringEscaping", test_serialize_stringEscaping),
586586
("test_serialize_invalid_json", test_serialize_invalid_json),
587587
("test_jsonReadingOffTheEndOfBuffers", test_jsonReadingOffTheEndOfBuffers),
588+
("test_jsonObjectToOutputStreamBuffer", test_jsonObjectToOutputStreamBuffer),
589+
("test_jsonObjectToOutputStreamFile", test_jsonObjectToOutputStreamFile),
590+
("test_invalidJsonObjectToStreamBuffer", test_invalidJsonObjectToStreamBuffer),
591+
("test_jsonObjectToOutputStreamInsufficeintBuffer", test_jsonObjectToOutputStreamInsufficeintBuffer),
588592
]
589593
}
590594

@@ -759,4 +763,97 @@ extension TestNSJSONSerialization {
759763
XCTFail("Unknow json decoding failure")
760764
}
761765
}
766+
767+
func test_jsonObjectToOutputStreamBuffer(){
768+
let dict = ["a":["b":1]]
769+
do {
770+
let buffer = Array<UInt8>(repeating: 0, count: 20)
771+
let outputStream = NSOutputStream(toBuffer: UnsafeMutablePointer<UInt8>(buffer), capacity: 20)
772+
outputStream.open()
773+
let result = try JSONSerialization.writeJSONObject(dict.bridge(), toStream: outputStream, options: [])
774+
outputStream.close()
775+
if(result > -1) {
776+
XCTAssertEqual(NSString(bytes: buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue), "{\"a\":{\"b\":1}}")
777+
}
778+
} catch {
779+
XCTFail("Error thrown: \(error)")
780+
}
781+
}
782+
783+
func test_jsonObjectToOutputStreamFile() {
784+
let dict = ["a":["b":1]]
785+
do {
786+
let filePath = createTestFile("TestFileOut.txt",_contents: Data(capacity: 128)!)
787+
if filePath != nil {
788+
let outputStream = NSOutputStream(toFileAtPath: filePath!, append: true)
789+
outputStream?.open()
790+
let result = try JSONSerialization.writeJSONObject(dict.bridge(), toStream: outputStream!, options: [])
791+
outputStream?.close()
792+
if(result > -1) {
793+
let fileStream: InputStream = InputStream(fileAtPath: filePath!)!
794+
var buffer = [UInt8](repeating: 0, count: 20)
795+
fileStream.open()
796+
if fileStream.hasBytesAvailable {
797+
let resultRead: Int = fileStream.read(&buffer, maxLength: buffer.count)
798+
fileStream.close()
799+
if(resultRead > -1){
800+
XCTAssertEqual(NSString(bytes: buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue), "{\"a\":{\"b\":1}}")
801+
}
802+
}
803+
removeTestFile(filePath!)
804+
} else {
805+
XCTFail("Unable to create temp file")
806+
}
807+
}
808+
} catch {
809+
XCTFail("Error thrown: \(error)")
810+
}
811+
}
812+
813+
func test_jsonObjectToOutputStreamInsufficeintBuffer() {
814+
let dict = ["a":["b":1]]
815+
let buffer = Array<UInt8>(repeating: 0, count: 10)
816+
let outputStream = NSOutputStream(toBuffer: UnsafeMutablePointer<UInt8>(buffer), capacity: 20)
817+
outputStream.open()
818+
do {
819+
let result = try JSONSerialization.writeJSONObject(dict.bridge(), toStream: outputStream, options: [])
820+
outputStream.close()
821+
if(result > -1) {
822+
XCTAssertNotEqual(NSString(bytes: buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue), "{\"a\":{\"b\":1}}")
823+
}
824+
} catch {
825+
XCTFail("Error occurred while writing to stream")
826+
}
827+
}
828+
829+
func test_invalidJsonObjectToStreamBuffer() {
830+
let str = "Invalid JSON"
831+
let buffer = Array<UInt8>(repeating: 0, count: 10)
832+
let outputStream = NSOutputStream(toBuffer: UnsafeMutablePointer<UInt8>(buffer), capacity: 20)
833+
outputStream.open()
834+
XCTAssertThrowsError(try JSONSerialization.writeJSONObject(str.bridge(), toStream: outputStream, options: []))
835+
}
836+
837+
private func createTestFile(_ path: String,_contents: Data) -> String? {
838+
let tempDir = "/tmp/TestFoundation_Playground_" + NSUUID().UUIDString + "/"
839+
do {
840+
try FileManager.default().createDirectory(atPath: tempDir, withIntermediateDirectories: false, attributes: nil)
841+
if FileManager.default().createFile(atPath: tempDir + "/" + path, contents: _contents,
842+
attributes: nil) {
843+
return tempDir + path
844+
} else {
845+
return nil
846+
}
847+
} catch _ {
848+
return nil
849+
}
850+
}
851+
852+
private func removeTestFile(_ location: String) {
853+
do {
854+
try FileManager.default().removeItem(atPath: location)
855+
} catch _ {
856+
857+
}
858+
}
762859
}

0 commit comments

Comments
 (0)