Parsing json data using swift json - ios

I can’t get the JSON data of message using swiftyjson.
When i print JSON value is there. But, when i print(json["result"]["message"]) it is null
{
"result": [{
"message": "success",
"age": "25"
}]
}
let json = JSON(data:jdata)
print(json)
print(json["result"]["message"])

json["result"] seems to be an array, you have to cast it to array like
let array = json["result"].arrayValue
let message = array[0]["message"]

You result is of array type. And you have to set index of object.
Try:
var array = json["result"].arrayValue
print(array[0]["message"])
You can also check this question
Hope it helps

Try:
let json = JSON(data: jdata)
let message = json["result"].array?.first?["message"]
print(message)

Related

Alamofire 5.5 responseDecodable on JSON array

I am trying to decode an api response that just responds with an array. All the examples I see for using responseDecodable are a dictionary with a data key or something. But when I just pass [Movie].self into as the decoder I get:
failure(Alamofire.AFError.responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "name", intValue: nil), Swift.DecodingError.Context(codingPath: responseDecodable
I'm assuming I'm not doing this right, looking for some help
GET /request
Response:
[{"id": 1, "name": "test"}]
struct Movie: Codable, Hashable {
let id: Int
let name: String
}
AF.request("http://localhost/request", parameters: parameters)
.responseDecodable(of: [Movie].self) { response in
debugPrint(response)
}
You will need to first assign a variable to accept the JSON data. From there, you can display the result. To illustrate:
AF.request("http://localhost/request", parameters: parameters)
.responseDecodable(of: [Movie].self) { response in
let myresult = try? JSON(data: response.data!)
then print it:
debugPrint(myresult)
If your JSON data is sound, then you should have no problem receiving the data. If your JSON is nested, then, you can drill-down into it:
let myresult = try? JSON(data: response.data!)
let resultArray = myresult!["result"]
and so on.
As for the "KeyNotFound" error ... It's because of what you said ... it's looking for a dictionary key/value pair. That should be resolved once you try the above example. Also, it's good practice to place your "method" in your AF request. :)
According to the error, your JSON didn't return a name value, so check that's it's actually supposed to be that key, or mark the value as optional if it's not always returned. let name: String?

Parse Dictionary of Array of Dictionary in Swift 3

I am working on a project where I am getting a dictionary of an array which again containt the dictionary
My Json Response is
{
"code": 200,
"status": "OK",
"success": "true",
"message": "success",
"data": {
"vehicletypeData": [
{
"vehicle_type_id": "1",
"vehicle_type": "Any"
},
{
"vehicle_type_id": "11",
"vehicle_type": "Bike"
}
]
}
}
And I am parsing the data like
if response.success {
let resObj = response.responseObject as! Dictionary<String, Any>
let catArray = resObj["data"] as! Dictionary<String,Array<Dictionary<String,Any>>> // Crashes here
let vehicleData = catArray["vehicletypeData"] as! Array<Dictionary<String, Any>>
for vehicle in vehicleData {
self.jobCategories.append(PreJobVehicleData.mj_object(withKeyValues: vehicle))
}
}
I am trying to parse it in my model
Here I am getting an error like
- Could not cast value of type '__NSArrayM' (0x109b82e00) to 'NSDictionary' (0x109b832d8)
Any help will be Thankful.
Don't say
resObj["data"] as! Dictionary<String,Array<Dictionary<String,Any>>>
That's too specific. Just say
resObj["data"] as! [String:Any]
You know that when you get something by key out of that dictionary, it will be an array, but you can literally cross that bridge when you come to it.
The same rule applies to your other casts. Just cast to Swift dictionary or array using the broadest simplest possible type.
(Note that all this will be solved in Swift 4, where you can build a knowledge of the JSON structure right into your fetch.)
As you are parsing the nodes separately anyway avoid to cast to (more than two levels) nested types.
According to the error message the value for key data seems to be an array (Array<Dictionary<String, Any>>)
if response.success {
let resObj = response.responseObject as! Dictionary<String, Any>
let dataArray = resObj["data"] as! Array<Dictionary<String, Any>>
...
That implies however that the JSON output is wrong and I have no idea what's next...

How to read data inside JSON object in swift

[
{
"id": "dcf8df3f8ce5963d7fa8",
"title": "MySurvey",
"description": "Guest Survey"
}
]
Above is json data response from api. I've read above json data with SwiftyJSON in my ios project as follow.
let swiftyJsonVar = JSON(responseData.result.value!)
print(swiftyJsonVar["title"])
I can't read and print above json data. Please let me know how to read above json data with SwiftyJSON.
The response is Array not Dictionary, try to access this
let arr = swiftyJsonVar.arrayObject
print(arr[0]["title"])
print(arr[0]["id"])
print(arr[0]["description"])

How to convert a string into JSON using SwiftyJSON

The string to convert:
[{"description": "Hi","id":2,"img":"hi.png"},{"description": "pet","id":10,"img":"pet.png"},{"description": "Hello! :D","id":12,"img":"hello.png"}]
The code to convert the string:
var json = JSON(stringLiteral: stringJSON)
The string is converted to JSON and when I try to count how many blocks are inside this JSON (expected answer = 3), I get 0.
print(json.count)
Console Output: 0
What am I missing? Help is very appreciated.
Actually, there was a built-in function in SwifyJSON called parse
/**
Create a JSON from JSON string
- parameter string: Normal json string like '{"a":"b"}'
- returns: The created JSON
*/
public static func parse(string:String) -> JSON {
return string.dataUsingEncoding(NSUTF8StringEncoding)
.flatMap({JSON(data: $0)}) ?? JSON(NSNull())
}
Note that
var json = JSON.parse(stringJSON)
its now changed to
var json = JSON.init(parseJSON:stringJSON)
I fix it on this way.
I will use the variable "string" as the variable what contains the JSON.
1.
encode the sting with NSData like this
var encodedString : NSData = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding)!
un-encode the string encoded (this may be sound a little bit weird hehehe):
var finalJSON = JSON(data: encodedString)
Then you can do whatever you like with this JSON.
Like get the number of sections in it (this was the real question) with
finalJSON.count or print(finalJSON[0]) or whatever you like to do.
There is a built-in parser in SwiftyJSON:
let json = JSON.init(parseJSON: responseString)
Don't forget to import SwiftyJSON!
I'm using as follows:
let yourString = NSMutableString()
let dataToConvert = yourString.data(using: String.Encoding.utf8.rawValue)
let json = JSON(data: dataToConvert!)
print("\nYour string: " + String(describing: json))
Swift4
let json = string.data(using: String.Encoding.utf8).flatMap({try? JSON(data: $0)}) ?? JSON(NSNull())

parse JSON Array from GET request Alamofire Swift 2

I'm new to Swift, my task is to get data from GET request and present its data on UI. Below is my code:
let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
let headers = ["Authorization": "Basic \(base64Credentials)"]
Alamofire.request(.GET, myUrl, headers: headers)
.responseJSON{ JSON in
if let jsonResult = JSON as? Array<Dictionary<String, String>> {
let title = jsonResult[0]["title"]
print(title)
}
}
I'm able to get data with request but I don't know how to parse JSON object in some format (probably json array) that can be later used to present in TableView. Please help
Data example:
[
{
"title": "Sony",
"content": "Tech content",
"image": "http://google.com/content/device.jpg?06"
},
{
"title": "Nexus",
"content": "Nexus 6 is a new beginning",
"image": "http://google.com/content/device.jpg?01"
} ]
JSON data can be represented in different forms. It can be encoded as a string or converted into known data types on the platform. The main components of json are arrays, associative arrays (or dictionaries), and values.
The swift struct you are displaying reads as follows.
It's an array. Array content displayed here starts and ends with [] like [1,2,3] would be an array of ints.
The data in the the array a list of dictionaries. dictionary start and ends with {} . like {"key":"value"}
Those dictionaries contain the keys "title","content" and "image".
because you requested responseJSON from alamo file you will be returned a parsed structure and all you need to do read it like you would normal arrays and dictionaries as that is what it is.
You should read this documentation on how to make safe code that uses the above logic.
http://www.raywenderlich.com/82706/working-with-json-in-swift-tutorial

Resources