Skip to content

[swift-corelibs-foundation]-- Fixed JSON Deserialisation of string values with spaces at the start String #263

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
Apr 28, 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
7 changes: 6 additions & 1 deletion Foundation/NSJSONSerialization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,12 @@ private struct JSONReader {
}

func consumeStructure(ascii: UInt8, input: Index) throws -> Index? {
return try consumeWhitespace(input).flatMap(consumeASCII(ascii)).flatMap(consumeWhitespace)
switch ascii {
case Structure.QuotationMark:
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"
default:
return try consumeWhitespace(input).flatMap(consumeASCII(ascii)).flatMap(consumeWhitespace)
}
}

func consumeASCII(ascii: UInt8) -> (Index) throws -> Index? {
Expand Down
18 changes: 18 additions & 0 deletions TestFoundation/TestNSJSONSerialization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ extension TestNSJSONSerialization {
("test_deserialize_emptyArray", test_deserialize_emptyArray),
("test_deserialize_multiStringArray", test_deserialize_multiStringArray),
("test_deserialize_unicodeString", test_deserialize_unicodeString),
("test_deserialize_stringWithSpacesAtStart", test_deserialize_stringWithSpacesAtStart),


("test_deserialize_values", test_deserialize_values),
Expand Down Expand Up @@ -148,6 +149,23 @@ extension TestNSJSONSerialization {
}
}

func test_deserialize_stringWithSpacesAtStart(){

let subject = "{\"title\" : \" hello world!!\" }"
do {
guard let data = subject.bridge().dataUsingEncoding(NSUTF8StringEncoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String : Any]
XCTAssertEqual(result?["title"] as? String, " hello world!!")
} catch{
XCTFail("Error thrown: \(error)")
}


}

//MARK: - Array Deserialization
func test_deserialize_emptyArray() {
let subject = "[]"
Expand Down