I'm trying to parse json to an object but i get this error?
Here's the function:
private func unwrap(_ object: Any) -> Any {
switch object {
case let json as JSON:
return unwrap(json.object)
case let array as [Any]:
return array.map(unwrap)
case let dictionary as [String: Any]:
var unwrappedDic = dictionary
for (k, v) in dictionary {
unwrappedDic[k] = unwrap(v)
}
return unwrappedDic
default:
return object
}
}
but I'm getting this error:
EXC_BAD_ACCESS (code=2, address=0x16f9cbfe0)
Related
This question already has an answer here:
Swift 4 JSON Codable - value returned is sometimes an object, others an array
(1 answer)
Closed 3 years ago.
Let's say I have an array of JSON response from the GET method like :
[{
"id":"1",
"Name":"John Doe",
},{
"id":"2",
"Name":"Jane Doe",
}]
And from the POST method using id param I only have 1 object JSON response :
{
"id":"1",
"Name":"John Doe",
}
how can I write a method to decode both the JSON dynamically?
At the moment, this is what I'm using :
func convertJSON<T:Decodable>(result: Any?, model: T.Type) -> T? {
if let res = result {
do {
let data = try JSONSerialization.data(withJSONObject: res, options: JSONSerialization.WritingOptions.prettyPrinted)
return try JSONDecoder().decode(model, from: data)
} catch {
print(error)
return nil
}
} else {
return nil
}
}
The method can be used to decode a single object using dynamic model, but I just can't figure it out to handle a single object / an array of objects dynamically.
The most I can get with is just using a duplicate of the method but replacing T with
[T] in the method parameter and return type, if the response is an array.
I'm open to any suggestion, any help is appreciated, Thank You in advance.
Edit : If this question is duplicate of this , I'm not sure how the marked answer could be a solution.
One solution could be to always return [Model]?.
Inside your function first try to decode as Model, on success return an array with that single decoded object inside it. If this fails then try to decode as [Model], on success return the decoded object else return nil.
Using your sample JSONs I created a struct:
struct Person: Codable {
let id, name: String
enum CodingKeys: String, CodingKey {
case id
case name = "Name"
}
}
Then I created a struct with a couple of methods to decode from either a String or an optional Data.
struct Json2Type<T: Decodable> {
// From data to type T
static public func convertJson(_ data: Data?) -> [T]? {
// Check data is not nil
guard let data = data else { return nil }
let decoder = JSONDecoder()
// First try to decode as a single object
if let singleObject = try? decoder.decode(T.self, from: data) {
// On success return the single object inside an array
return [singleObject]
}
// Try to decode as multiple objects
guard let multipleObjects = try? decoder.decode([T].self, from: data) else { return nil }
return multipleObjects
}
// Another function to decode from String
static public func convertJson(_ string: String) -> [T]? {
return convertJson(string.data(using: .utf8))
}
}
Finally call the method you prefer:
Json2Type<Person>.convertJson(JsonAsDataOrString)
Update: #odin_123, a way to have either a Model or [Model] as return value can be accomplish using an enum. We can even add the error condition there to avoid returning optionals. Let's define the enum as:
enum SingleMulipleResult<T> {
case single(T)
case multiple([T])
case error
}
Then the struct changes to something like this:
struct Json2Type<T: Decodable> {
static public func convertJson(_ data: Data?) -> SingleMulipleResult<T> {
guard let data = data else { return .error }
let decoder = JSONDecoder()
if let singleObject = try? decoder.decode(T.self, from: data) {
return .single(singleObject)
}
guard let multipleObjects = try? decoder.decode([T].self, from: data) else { return .error }
return .multiple(multipleObjects)
}
static public func convertJson(_ string: String) -> SingleMulipleResult<T> {
return convertJson(string.data(using: .utf8))
}
}
You can call it the same way we did before:
let response = Json2Type<Person>.convertJson(JsonAsDataOrString)
And use a switch to check every possible response value:
switch(response) {
case .single(let object):
print("One value: \(object)")
case .multiple(let objects):
print("Multiple values: \(objects)")
case .error:
print("Error!!!!")
}
I receive from a post request, this JSON:
"clinic_info": {
"city": "Querétaro",
"state": "Querétaro",
"country": "México",
"phone": null,
"ext": null,
"coords": "20.6046089,-100.37826050000001",
"location": "Querétaro"
}
But when it is empty the JSON is:
"clinic_info": []
This produces an error: Expected to decode Dictionary but found an array instead.
This is happening because decoder want dictionary and your JSON is array
Need to check before decoding that JSON response is dictionary or Array and do decoding accordingly.
If you find Dictionary then do like this
let myData = try JSONDecoder().decode(YourModel.self, from: jsonData)
If you find Array then do like this
let myData = try JSONDecoder().decode([YourModel].self, from: jsonData)
You can do it using try, throw like that
import Foundation
struct ClinicData: Codable {
let clinicInfo: ClinicInfo?
enum CodingKeys: String, CodingKey {
case clinicInfo = "clinic_info"
}
}
struct ClinicInfo: Codable {
let city, state, country: String
let coords, location: String
}
// MARK: Convenience initializers
extension ClinicData {
init(data: Data) throws {
self = try JSONDecoder().decode(ClinicData.self, from: data)
}
init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
func jsonData() throws -> Data {
return try JSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
**get clinicInfo**
if let clinicData = try? ClinicData.init(data: Data()), let clinicInfo =
clinicData.clinicInfo{
}
The service that provides those JSON responses replies with:
"clinic_info": { ... }
Where ... is a valid JSON object.
But when it is empty, you are saying it looks like this:
"clinic_info": []
Notice the [] that say this is an empty array of objects.
You might want to change the service response (if possible), since it looks inconsistent to me having it return an object when it has valid data, and an array when there is no valid data.
The error message you are getting is clear:
Expected to decode Dictionary but found an array instead.
It expected an object {}, but found an array [].
The Array class has a method for this.
Using typeof will always return "object".
The code below shows how to use the isArray() method in the Array class.
const obj = {
_array: [],
_object: {}
}
console.log(Array.isArray(obj._array)); // true
console.log(Array.isArray(obj._object)); // false
I am trying to parse JSON data using SwiftyJSON into an array to use in my TableView. However even though I can successfully request the data and parse it into an array, I cannot return it from the getObjects function as it is done asynchronously. I have tried to use a completion handler, and after following several tutorials it seems I am missing something.
Does anybody know how I can return the array to use in my TableViewController ?
Table View Controller
let objects = [Objects]()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let urlString = "URLSTRING"
objects = dataManager.getObjects(urlString)
print("objects in view controller products array \(objects.count)")
self.tableView.reloadData
}
Request Functions
class DataManager {
func requestObjects(_ stringUrl: String, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void) {
print("Request Data")
Alamofire.request(stringUrl, method: .get).validate().responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
print("responce success")
success(json)
case .failure(let error):
print(error)
} //End of switch statement
} //End of alamofire request
} //End of request function
func getObjects(_ urlString:String) -> [Object] {
var objects = [Object]()
requestObjects(urlString, success: { (JSONResponse) -> Void in
let json = JSONResponse
for item in json["items"] {
let title = item.1["title"].string
objects.append(Object(title: title!))
}
print("Number of objects = \(objects.count)")
}) {
(error) -> Void in
print(error)
}
print(objects) // Prints empty array
return objects // Array is empty
}
}
You need to use completionHandler to return data to TableViewController.
func getObjects(completionHandler : #escaping ([Object]) -> (),_ urlString:String) -> [Sneaker] {
var objects = [Object]()
requestObjects(urlString, success: { (JSONResponse) -> Void in
let json = JSONResponse
for item in json["items"] {
let title = item.1["title"].string
objects.append(Object(title: title!))
}
completionHandler(objects)
print("Number of objects = \(objects.count)")
}) {
(error) -> Void in
print(error)
}
print(objects) // Prints empty array
return objects // Array is empty
}
}
In your TableViewController
dataManager.getObject(completionHandler: { list in
self.objects = list
}, urlString)
There could be some syntax error i didnt test it
If I build a Swift dictionary, i.e. [String: Any] how can I return that as JSON? I tried this, but it gives me the error: Argument labels '(node:)' do not match any available overloads.
drop.get("test") { request in
var data: [String: Any] = [:]
data["name"] = "David"
data["state"] = "CA"
return try JSON(node: data)
}
Convoluted as heck, but this allows you to use [String:Any].makeNode(), as long as the internals are NodeRepresentable, NSNumber based, or NSNull :) --
import Node
enum NodeConversionError : LocalizedError {
case invalidValue(String,Any)
var errorDescription: String? {
switch self {
case .invalidValue(let key, let value): return "Value for \(key) is not NodeRepresentable - " + String(describing: type(of: value))
}
}
}
extension NSNumber : NodeRepresentable {
public func makeNode(context: Context = EmptyNode) throws -> Node {
return Node.number(.double(Double(self)))
}
}
extension NSString : NodeRepresentable {
public func makeNode(context: Context = EmptyNode) throws -> Node {
return Node.string(String(self))
}
}
extension KeyAccessible where Key == String, Value == Any {
public func makeNode(context: Context = EmptyNode) throws -> Node {
var mutable: [String : Node] = [:]
try allItems.forEach { key, value in
if let _ = value as? NSNull {
mutable[key] = Node.null
} else {
guard let nodeable = value as? NodeRepresentable else { throw NodeConversionError.invalidValue(key, value) }
mutable[key] = try nodeable.makeNode()
}
}
return .object(mutable)
}
public func converted<T: NodeInitializable>(to type: T.Type = T.self) throws -> T {
return try makeNode().converted()
}
}
With that header you can:
return try JSON(node: data.makeNode())
JSON cannot be initialized from a [String : Any] dictionary because Any is not convertible to Node.
There are only a limited number of types that Node can be. (See Node source). If you know your objects are all going to be the same type, use a dictionary that only allows that type. So for your example, [String : String].
If you're going to be getting data from the request, you can try using request.json as is used in the documentation here.
EDIT:
Another (possibly better) solution would be to make your dictionary [String: Node] and then you can include any type that conforms to Node. You may have to call the object's makeNode() function to add it to the dictionary though.
I have a JSON String that follows a format like { name: "John" } and not { "name" : "John"} and that is resulting in a nil whenever I try to access the name key because:
Error Domain=NSCocoaErrorDomain Code=3840 "No string key for value in object around character 1."
I am looking for a function that fixes/parses/formats this JSON file into something readable? How do sites like JSON Format do it?
Funny enough, { name: "John" } makes a valid JSON object in Javascript. So your problem now becomes finding a Javascript intepreter for Swift!
There's one built-in to recent versions of Mac OS X and iOS: WKWebView. It's a web rendering engine with a Javascript parser. Link your target with WebKit and try this:
import WebKit
class MyJSONParser {
private static let webView = WKWebView()
class func parse(jsonString: String, completionHandler: (AnyObject?, NSError?) -> Void) {
self.webView.evaluateJavaScript(jsonString, completionHandler: completionHandler)
}
}
Usage:
let str = "{ firstName: 'John', lastName: 'Smith' }"
// You must assign the JSON string to a variable or the Javascript
// will return void. Note that this runs asynchronously
MyJSONParser.parse("tmp = \(str)") { result, error in
guard error == nil else {
print(error)
return
}
if let dict = result as? [String: String] {
print(dict)
} else {
print("Can't convert to Dictionary")
}
}
Swift 3
import WebKit
class MyJSONParser {
private static let webView = WKWebView()
class func parse(jsonString: String, completionHandler: #escaping (Any?, Error?) -> Void) {
self.webView.evaluateJavaScript(jsonString, completionHandler: completionHandler)
}
}
let str = "{ firstName: 'John', lastName: 'Smith' }"
// You must assign the JSON string to a variable or the Javascript
// will return void. Note that this runs asynchronously
MyJSONParser.parse(jsonString: "tmp = \(str)") { result, error in
guard error == nil else {
print(error!)
return
}
if let dict = result as? [String: String] {
print(dict)
} else {
print("Can't convert to Dictionary")
}
}