Skip to content
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

fix:适配基本数据类型数组的解码问题,不仅限于对象数组; 例如: #424

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
8 changes: 6 additions & 2 deletions Source/Deserializer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ public class JSONDeserializer<T: HandyJSON> {
}
}

/// if the JSON field found by `designatedPath` in `json` is representing a array, such as `[{...}, {...}, {...}]`,
/// if the JSON field found by `designatedPath` in `json` is representing a array, such as `[{...}, {...}, {...}]`, `[1, 2, 3]` , `["1", "2", "3"]`
/// this method converts it to a Models array
public static func deserializeModelArrayFrom(json: String?, designatedPath: String? = nil) -> [T?]? {
guard let _json = json else {
Expand All @@ -135,7 +135,11 @@ public class JSONDeserializer<T: HandyJSON> {
let jsonObject = try JSONSerialization.jsonObject(with: _json.data(using: String.Encoding.utf8)!, options: .allowFragments)
if let jsonArray = getInnerObject(inside: jsonObject, by: designatedPath) as? [Any] {
return jsonArray.map({ (item) -> T? in
return self.deserializeFrom(dict: item as? [String: Any])
if let dic = item as? [String: Any] {
return self.deserializeFrom(dict: dic)
}else{
return item as? T
}
})
}
} catch let error {
Expand Down
12 changes: 10 additions & 2 deletions Source/Serializer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,16 @@ public extension HandyJSON {

public extension Collection where Iterator.Element: HandyJSON {

func toJSON() -> [[String: Any]?] {
return self.map{ $0.toJSON() }
func toJSON() -> [Any?] { // a array, such as `[{...}, {...}, {...}]`, `[1, 2, 3]` , `["1", "2", "3"]`
return self.map{
if let _ = $0 as? String {
return $0
}else if let _ = $0 as? Int {
return $0
}else{
return $0.toJSON()
}
}
}

func toJSONString(prettyPrint: Bool = false) -> String? {
Expand Down