Skip to content

Commit 4458343

Browse files
committed
add string data for initialize
1 parent edf9cbb commit 4458343

File tree

2 files changed

+24
-16
lines changed

2 files changed

+24
-16
lines changed

Sources/Lookup/Lookup.swift

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -103,34 +103,35 @@ public struct Lookup: Swift.CustomStringConvertible, Swift.CustomDebugStringConv
103103
}
104104
}
105105

106-
private init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws {
107-
let object: Any = try JSONSerialization.jsonObject(with: data, options: opt)
108-
self.init(jsonObject: object)
106+
private init(data: Data, options opt: JSONSerialization.ReadingOptions = []) {
107+
do {
108+
let object: Any = try JSONSerialization.jsonObject(with: data, options: opt)
109+
self.init(jsonObject: object)
110+
} catch let error as NSError {
111+
// Code=3840 "JSON text did not start with array or object and option to allow fragments not set. around line 1, column 0."
112+
if error.code == 3840, let str = String(data: data, encoding: .utf8) { // try to initialize using a string
113+
self.init(jsonObject: str)
114+
} else {
115+
self.init(jsonObject: NSNull())
116+
}
117+
}
109118
}
110119

111-
private init(jsonString: String) throws {
120+
private init(jsonString: String) {
112121
guard let stringData = jsonString.data(using: .utf8) else {
113122
self.init(jsonObject: NSNull())
114123
return
115124
}
116-
try self.init(data: stringData)
125+
self.init(data: stringData)
117126
}
118127

119-
/// Support JSON-Data, String of JSON, Array, Dictionary, Struct object and Class object
128+
/// Support `JSON-Data`, `String-Data`, `String of JSON`, `Array`, `Dictionary`, `Struct object` and `Class object`
120129
public init(_ object: Any) {
121130
switch object {
122131
case let str as String:
123-
do {
124-
try self.init(jsonString: str)
125-
} catch {
126-
self.init(jsonObject: str)
127-
}
132+
self.init(jsonString: str)
128133
case let data as Data:
129-
do {
130-
try self.init(data: data)
131-
} catch {
132-
self.init(jsonObject: NSNull())
133-
}
134+
self.init(data: data)
134135
default:
135136
self.init(jsonObject: object)
136137
}

Tests/LookupTests/LookupTests.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,13 @@ final class LookupTests: QuickSpec {
3939
describe("Lookup tests") {
4040

4141
context("test initialization") {
42+
it("data string initialization") {
43+
let str = "Its a string..."
44+
let data = str.data(using: .utf8)!
45+
let lookup = Lookup(data)
46+
expect(lookup.string) == str
47+
}
48+
4249
it("jsonString initialization") {
4350
let jsonString = "{\"name\": \"lookup\"}"
4451
let lookup = Lookup(jsonString)

0 commit comments

Comments
 (0)