SwiftyJson get value of json from complicated structure of JSON - ios

This my json.file:
[
{
"date_range": "2016-11-01-2016-12-31",
"order_status_id": 3,
"jobs": [
{
"date": "2016-11-14",
"job": [
{
"id": 143608,
"pickup_worker_id": null,
"drop_off_worker_id": 57
}
]
}
]
}
{
"date_range": "2016-11-01-2016-12-31",
"order_status_id": 2,
"jobs": [
{
"date": "2016-11-16",
"job": [
{
"id": 143238,
"pickup_worker_id": null,
"drop_off_worker_id": 12
},
{
"id": 13218,
"pickup_worker_id": null,
"drop_off_worker_id": 42
}
]
},
{
"date": "2016-11-19",
"job": [
{
"id": 141238,
"pickup_worker_id": null,
"drop_off_worker_id": 12
}
]
}
]
}
]
This my code for swiftyjson:
Alamofire.request(Constants.web_api+api_get_orders, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: Constants.headers ).responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
print("All Data JSON \(swiftyJsonVar)")
print("date range1\(swiftyJsonVar["date_range"])")
print("date range2\(swiftyJsonVar["date_range"].stringValue)")
print("jobs1 \(swiftyJsonVar["jobs"].arrayObject)")
print("jobs2 \(swiftyJsonVar["jobs"].array)")
print("jobs3 \(swiftyJsonVar["jobs"])")
print("jobs date \(swiftyJsonVar["jobs"]["date"].stringValue)")
print("jobs date \(swiftyJsonVar["jobs"]["job"]["drop_off_worker_id"].stringValue)")
}
The output , all is null or nil except All Data JSON (swiftyJsonVar). How can I get value of date_range, drop_off_worker_id ? I really hope someone can help me. I spend a lot of time for solve it but still can't solve it.

Your JSON response is Array not Dictionary, so you need to access its first object to get the detail you want.
if let dateRange = swiftyJsonVar[0]["date_range"].string {
print(dateRange)
}
if let worker_id = swiftyJsonVar[0]["jobs"][0]["job"][0]["drop_off_worker_id"].int {
print(worker_id)
}
Edit: If you have multiple object in your root than get all the dateRange and worker_id in for loop.
for subJson in swiftyJsonVar.array {
if let dateRange = subJson["date_range"].string {
print(dateRange)
}
for jobsJson in subJson["jobs"].array {
for jobJson in jobsJson["job"].array {
if let worker_id = jobJson["drop_off_worker_id"].int {
print(worker_id)
}
}
}
}

Please try, by referring the index of the element in the array.
Alamofire.request(Constants.web_api+api_get_orders, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: Constants.headers)
.responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
print("All Data JSON \(swiftyJsonVar)")
print("date range1\(swiftyJsonVar[0]["date_range"])")
print("date range2\(swiftyJsonVar[0]["date_range"].stringValue)")
print("jobs1 \(swiftyJsonVar[0]["jobs"].arrayObject)")
print("jobs2 \(swiftyJsonVar[0]["jobs"].array)")
print("jobs3 \(swiftyJsonVar[0]["jobs"])")
print("jobs date \(swiftyJsonVar[0]["jobs"]["date"].stringValue)")
print("jobs date \(swiftyJsonVar[0]["jobs"]["job"]["drop_off_worker_id"].stringValue)")
}

Related

post array of json with alamofire swift

How can i post array of json objects with alamofire in swift?
my final data (which i want to post) looks like:
temp = [{
"time": 1,
"score": 20,
"status": true,
"answer": 456
},
{
"time": 0,
"score": 0,
"status": false,
"answer": 234
},
{
"time": 0,
"score": 20,
"status": true,
"answer": 123
}
]
i got hint that i have to create custom parameter encoding but i am confused how can i do that. Someone please help me.
my current code looks like
let parameters: Parameters = [
"answers": temp,
"challenge_date": "2019-03-01"
]
Alamofire.request("...url", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
.responseJSON {
response in
if
let status = response.response ? .statusCode {
let classFinal: JSON = JSON(response.result.value!)
if (status > 199 && status < 300) {
self.dismiss(animated: true)
} else {
}
}
}
In your code change method .put to .post, and not required to SVProgressHUD.dismiss() in else, because you already dismiss before if else part
Also, you need to convert your JSON string(temp variable) to array and then pass with the parameter.
let parameters: Parameters = [
"answers": temp,
"challenge_date": "2019-03-01"
]
Alamofire.request("...url", method: .post, parameters: parameters, encoding: JSONEncoding.default , headers: headers)
.responseJSON { response in
if let status = response.response?.statusCode {
let classFinal : JSON = JSON(response.result.value!)
SVProgressHUD.dismiss()
if status > 199 && status < 300 {
self.dismiss(animated: true)
}
}
}
I hope your Parameters class follows Codable protocol.
As far as I see, you are getting an error parsing that object to JSON. Hence that is the source of your error.
Could you also add code for your Parameters class / struct
First, convert your Temp
Array into String
than pass in that in parameters of Alamofire.
extension NSArray {
func toJSonString(data : NSArray) -> String {
var jsonString = "";
do {
let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
} catch {
print(error.localizedDescription)
}
return jsonString;
}
}

swift getting all values of a dictionary and passing to viewcontroller using almaofire

Hi have an application which collects data from an api and I use Alamofire and swiftyJSON. the current challenge I am facing now is that I have different dictionaries in one array and I want to be able to retun back specific items in the dictionary. this is the array I am working with
Json
[
{
"images": [
{
"id": 8,
"original": "http://127.0.0.1:8000/media/images/products/2018/05/f3.jpg",
"caption": "",
"display_order": 0,
"date_created": "2018-05-26T17:24:34.762848Z",
"product": 13
},
{
"id": 9,
"original": "http://127.0.0.1:8000/media/images/products/2018/05/f5.jpg",
"caption": "",
"display_order": 1,
"date_created": "2018-05-26T17:24:34.815214Z",
"product": 13
},
{
"id": 10,
"original": "http://127.0.0.1:8000/media/images/products/2018/05/f2.jpg",
"caption": "",
"display_order": 2,
"date_created": "2018-05-26T17:25:19.117271Z",
"product": 13
},
{
"id": 11,
"original": "http://127.0.0.1:8000/media/images/products/2018/05/f4.jpg",
"caption": "",
"display_order": 3,
"date_created": "2018-05-26T17:25:19.155159Z",
"product": 13
}
]
}
]
get a single image is like this
Alamofire.request(URL, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: HEADER).responseJSON { (response) in
if response.result.error == nil {
guard let data = response.data else {return}
do {
if let json = try JSON(data: data).array {
for item in json {
let images = item["images"][0]["original"].stringValue
....
this returns only the indexed image.[0] if it is set to [1] it returns the indexed image at 1.
how do I return all the images so that I can loop through all and display in a collection view controller. more codes would be supplied on request.
You can dit it Like that :
if let json = try? JSON(data: data).arrayValue {
for item in json {
let imagesList = item["images"].arrayValue
let imagesURL = imagesList.map {$0["original"].string}.compactMap({$0})
if imagesURL.count > 0{
print( imagesURL[0])
}
}
}
Or:
do {
let json = try JSON(data: data).array
json?.forEach({ (item) in
let imagesList = item["images"].arrayValue
let imagesURL = imagesList.map {$0["original"].string}.compactMap({$0})
if imagesURL.count > 0{
print( imagesURL[0])
}
})
} catch {
print(error.localizedDescription)
}

swift parsing desc and parsing selected element

Swift parsing desc and parsing selected element. I want to parse desc and after parsing desc parse desc content. thanks swift parsing desc and parsing selected element.
I have tried different methods. Does anyone have an idea on how we can make it possible? I tried the following code:
**Code for getting the data**
func demoApi1() {
Alamofire.request("", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
guard let json = response.result.value as! [[String:Any]]? else{ return}
print("Ang Response: , \(json)")
for item in json {
self.getAllDetail.append(item )
if let desc = item["dec"] as? String {
self.titleArray.append(desc)
print("motherfucker:" , self.titleArray)
}
}
if !self.getAllDetail.isEmpty{
DispatchQueue.main.async {
}
}
break
case .failure(_):
print("Error")
break
}
}
}
Response:
Ang Response [["status": {
name = ongoing;
}, "sched": 2018-04-10T14:22:00+08:00, "desc": asdasdasdsa, "id": 224, "reward": 1.00, "parent": das, "child": dasdas, "date_created": 2018-04-19T15:54:24.657644+08:00, "name": sad, "occurrence": {
name = once;
}, "type": , "date_modified": 2018-04-19T15:54:24.703520+08:00], ["status": {
name = ongoing;
}, "sched": 2018-04-19T15:54:24.657644+08:00, "desc": {
"questions" : [
{
"b" : 2,
"a" : 1
},
{
"b" : 3,
"a" : 2
},
{
"b" : 2,
"a" : 8
},
{
"b" : 9,
"a" : 7
},
{
"b" : 3,
"a" : 6
}
],
"operation" : "addition"
}, "id": 226, "reward": 1.00, "parent": shit, "child": , "date_created": 2018-04-23T14:16:35.739436+08:00, "name": chorename, "occurrence": {
name = once;
}, "type": homework, "date_modified": 2018-04-23T14:16:35.790237+08:00]]
String to Dictionary:
func stringToDictionary(_ strToJSON : String)-> [String:Any]{
print("JsonString:\(strToJSON)")
let data = strToJSON.data(using: .utf8)
var dict = [String:Any]()
do {
dict = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
return dict
}
catch let error as NSError {
print("Error is:\(error)")
}
return dict
}
Use it like this:
let dictConv = stringToDictionary("your_string")
print(dictConv)

How to loop through JSON data in SwiftyJSON

I have a JSON data with structure and I don't know how to use for-loop with SwiftyJSON to get each sections entries of "path" and "updated" value. Anyone can help? Thanks.
var jsonData = "{
"css":[
{
"path": "style.css",
"updated": "12432"
},
{
"path": "base.css",
"updated": "34627"
},
],
"html":[
{
"path": "home.htm",
"updated": "3223"
},
{
"path": "about",
"updated": "3987"
}
]
}
"
I tried to code part of for-loop
let json = JSON(jsonData)
for ( ) in json {
let filepath =
let updated =
// do searching another json to found file exists and updates
}
It's on the README, under the section named "loop": https://github.com/SwiftyJSON/SwiftyJSON#loop
// If json is .Dictionary
for (key,subJson):(String, JSON) in json {
//Do something you want
}
// If json is .Array
// The `index` is 0..<json.count's string value
for (index,subJson):(String, JSON) in json {
//Do something you want
}
Applied to your specific JSON structure:
let jsonData = """
{
"css": [
{
"path": "style.css",
"updated": "12432"
},
{
"path": "base.css",
"updated": "34627"
}
],
"html": [
{
"path": "home.htm",
"updated": "3223"
},
{
"path": "about",
"updated": "3987"
}
]
}
""".data(using: .utf8)!
let json = JSON(data: jsonData)
for (_, subJson):(String, JSON) in json {
for (_, subJson):(String, JSON) in subJson {
let filepath = subJson["path"].stringValue
let updated = subJson["updated"].stringValue
print(filepath + " ~ " + updated)
}
}
Using Swift 4 Codable:
struct FileInfo: Decodable {
let path, updated: String
}
let dec = try! JSONDecoder().decode([String:[FileInfo]].self,from: jsonData)
print(dec)
As per your JSON structure, use this :
for (index,subJson):(String, JSON) in json {
print(index) // this prints "css" , "html"
for (key,subJson):(String, JSON) in subJson {
let filepath = subJson["path"]
let updated = subJson["updated"]
}
}

swiftyjson getting string from json array

I am using alamofire and swiftyjson to get it. I need to get string "ubus_rpc_session", I tryed this way, but I get an array, I need to get string. Could you help me?
Alamofire.request(URL, method: .post, parameters: param, encoding: JSONEncoding.default).responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
let token = json["result"].arrayValue.map({$0["ubus_rpc_session"].stringValue})
print(token)
{ "jsonrpc":"2.0",
"id":1,
"result":[
0,
{
"ubus_rpc_session":"07e111d317f7c701dc4dfde1b0d4862d",
"timeout":300,
"expires":300,
"acls":{
"access-group":{
"superuser":[
"read",
"write"
],
"unauthenticated":[
"read"
]
},
"ubus":{
"*":[
"*"
],
"session":[
"access",
"login"
]
},
"uci":{
"*":[
"read",
"write"
]
}
},
"data":{
"username":"root"
}
}
]
}
Try this
//Getting an array of string from a JSON Array(In their documents)
let arrayNames = json["users"].arrayValue.map({$0["name"].stringValue})
if let tempArray = json["result"].arrayValue {
for item in tempArray {
print(item)
if let title = item["ubus_rpc_session"].string {
println(title)
}
}
}
Or check this
let value = tempArray[1].dictionaryObject!
print(value["ubus_rpc_session"]!)

Resources