Skip to content

Commit e96c418

Browse files
Salman JamilSalman Jamil
authored andcommitted
-- Fixed JSON Deserialisation of string values with spaces at the start of string --
1 parent dc4fa2d commit e96c418

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

Foundation/NSJSONSerialization.swift

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,12 @@ private struct JSONReader {
306306
}
307307

308308
func consumeStructure(ascii: UInt8, input: Index) throws -> Index? {
309-
return try consumeWhitespace(input).flatMap(consumeASCII(ascii)).flatMap(consumeWhitespace)
309+
switch ascii {
310+
case Structure.QuotationMark:
311+
return try consumeWhitespace(input).flatMap(consumeASCII(ascii)) // for strings we don't consume(ignore) the whitespaces after the starting Quotation Mark because they are part of string e.g in "{\"title\" : \" hello world!!\" }" the value should be " hello world!!" instead of "hello world"
312+
default:
313+
return try consumeWhitespace(input).flatMap(consumeASCII(ascii)).flatMap(consumeWhitespace)
314+
}
310315
}
311316

312317
func consumeASCII(ascii: UInt8) -> (Index) throws -> Index? {

TestFoundation/TestNSJSONSerialization.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ extension TestNSJSONSerialization {
9292
("test_deserialize_emptyArray", test_deserialize_emptyArray),
9393
("test_deserialize_multiStringArray", test_deserialize_multiStringArray),
9494
("test_deserialize_unicodeString", test_deserialize_unicodeString),
95+
("test_deserialize_stringWithSpacesAtStart", test_deserialize_stringWithSpacesAtStart),
9596

9697

9798
("test_deserialize_values", test_deserialize_values),
@@ -148,6 +149,23 @@ extension TestNSJSONSerialization {
148149
}
149150
}
150151

152+
func test_deserialize_stringWithSpacesAtStart(){
153+
154+
let subject = "{\"title\" : \" hello world!!\" }"
155+
do {
156+
guard let data = subject.bridge().dataUsingEncoding(NSUTF8StringEncoding) else {
157+
XCTFail("Unable to convert string to data")
158+
return
159+
}
160+
let result = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String : Any]
161+
XCTAssertEqual(result?["title"] as? String, " hello world!!")
162+
} catch{
163+
XCTFail("Error thrown: \(error)")
164+
}
165+
166+
167+
}
168+
151169
//MARK: - Array Deserialization
152170
func test_deserialize_emptyArray() {
153171
let subject = "[]"

0 commit comments

Comments
 (0)