How to access nested JSON in brackets in Swift? - arrays

I have a JSON response which is in brackets and I struggle to access the inner fields e.g. display_name with Swift. How can I do that?
Optional(["result": {
user = {
"display_name" = "Max Test";
email = "test.max#gmail.com";
"fb_id" = 10209982554704497;
roles = (
stu
);
schools = "<null>";
};
}])
The code I used to access the JSON:
self.restApi.getProfileDetails() {responseObject, error in
//parse down the first layer of array
let response = responseObject as? [String:AnyObject]
print("response object when MyDetailsController opened")
print(response)
let result = response!["result"] as? [AnyObject]
print("result object")
print(result)
//parse down the second layer of JSON object
if let result = response!["result"] as? [AnyObject] {
print("result object when MyDetailsController opened")
// work with the content of "result", for example:
if let user = result[0] as? [String:AnyObject]{
print(user)
let displayName = user["display_name"]
print("displayName")
print(displayName)
}
}
It seems that I address the result in the wrong way as it is always nil:
The console output:
result object
nil

In response result is dictionary not array, try to get like this
let result = response!["result"] as? [String:AnyObject]

1-Get the result object from response
2-Get the user object from result object
3-Get the user info as String from user object .
let response = responseObject as? [String: AnyObject]
let result = response!["result"] as? [String: AnyObject]
if let user = result!["user"] as? [String: AnyObject] {
let displayName = user["display_name"] as? String
let email = user["email"] as? String
}

Related

ios swfit - assign list of AnyObject to dictionary key

so i want to assign a list of AnyObject to a key of a dictionary with the structure [String:AnyObject]
here is my code:
let list = try JSONSerialization.jsonObject(with: newData, options: .allowFragments) as! [AnyObject]
let parsedResult = [String:AnyObject]()
parsedResult["dataList"] = list
callback(false, parsedResult)
im parsing data from an http request. i get this error:
Cannot assign value of type [AnyObject] to type AnyObject?
isn't a list of AnyObject, still an object?
Change:
let parsedResult = [String:AnyObject]()
To:
var parsedResult: [String: Any] = [ : ]
And by the way declare parsedResult as var to be able to do parsedResult["dataList"] = list.
For your other issue that you placed a comment on, do this instead:
if let account = data?["account"] as? [String: Any], let accountKey = account["key"] as? Int { ... }

Retrieve JSON data in swift

I can't retrieve and print the jobDate data. what's wrong my code?
let retrievetime = UserDefaults().value(forKey: "retrieve")as? NSDictionary
print(retrievetime!)
if let job = retrievetime!["jobs"] as? [String:Any], let jobTitle = job["jobDate"] as? String {
self.navigationItem.title = jobTitle
print(jobTitle)
}
//self.navigationItem.title = "Test"
print retrieve time! json output:
{
jobs =({
jobDate = "2017-08-31";
jobEndTime = 1504144800;
jobID = 87;
jobTime = 1504137600;
});
message = "Retrieve Sucessfully";
result = success;
}
First of all use use the standard singleton instance and optional bindings to safely get data from UserDefaults – unless you registered the key/value pairs.
Second of all never use value(forKey with UserDefaults and never use NSDictionary in Swift unless the compiler tells you to do.
Finally as mentioned in the comments the value for key jobs – as the plural form implies – is an array, you have to get the first object of the array
if let retrievetime = UserDefaults.standard.object(forKey: "retrieve") as? [String:Any] {
print(retrievetime)
if let jobs = retrievetime["jobs"] as? [[String:Any]],
let job = jobs.first,
let jobTitle = job["jobDate"] as? String {
self.navigationItem.title = jobTitle
print(jobTitle)
}
}
let retrievetime = UserDefaults().value(forKey: "retrieve")as? NSDictionary
print(retrievetime!)
if let job = retrievetime!["jobs"] as? [String:Any], let jobTitle = ((retrievetime!["jobs"] as? [String:Any])[0] as? NSDictionary)["jobDate"] as? String {
self.navigationItem.title = jobTitle
print(jobTitle)
}
//self.navigationItem.title = "Test"

Swift3 get element from array

I have a json string converted to string array like below:
let str = "{ \"dtResult\": [ { \"itmdtl_item_no\": \"AO406705959SE3\" }, { \"itmdtl_item_no\": \"AO406708959SE3\" } ] }"
let data = str.data(using: String.Encoding.utf8, allowLossyConversion: false)!
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
let result = json["dtResult"] as? [[String:Any]] ?? [ ]
let item = result[0] as! [String:Any]
print(item)
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
When i print out the result of item, i got the value like this:
["itmdtl_item_no": AO406705959SE3]
But i just want the string "AO406705959SE3", how can i do? Thanks.
First of all don't write
let result = json["dtResult"] as? [[String:Any]] ?? [ ]
If result is nil or empty the app will crash on result[0]
Instead write to check if the array exists and is not empty
if let result = json["dtResult"] as? [[String:Any]], !result.isEmpty {
let item = result[0] as! [String:Any]
// Now get the value for key "itmdtl_item_no"
if let itemNo = item["itmdtl_item_no"] as? String {
print(itemNo)
}
}

Swift Array sort with JSON

Data:
tried get data from JSON
has code with Swift run on Playground
var roadWayStatusArray = [AnyObject]()
let url = URL(string: "http://od.moi.gov.tw/data/api/pbs")
let data = try? Data(contentsOf: url!)
let json = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
if let results = json as? [String : AnyObject] {
if let result = results["result"] as? [[String : AnyObject]] {
for data in result {
let happendate = data["happendate"] as? String
roadWayStatusArray.append(data as AnyObject!)
}
}
}
I has tried using roadWayStatusArray.sort(by: >) but Xcode report me Ambiguous reference member '>'
How to create sort by hapendate or happentime
Your roadWayStatusArray is an array of AnyObject. There is no > operator defined for AnyObject.
The objects in roadWayStatusArray are actually dictionaries that look like this:
{
UID = "10602090007-0";
areaNm = "\U4e2d\U5c71\U9ad8\U901f\U516c\U8def-\U570b\U9053\Uff11\U865f";
comment = "\U5317\U4e0a.\U4e2d\U58e2\U670d\U52d9\U5340 \U51fa\U53e3\U531d\U9053\U4e2d \U53f3\U5074 \U5c0f\U5ba2\U8eca\U505c\U653e\Uff0c\U99d5\U99db\U7591\U4f3c\U7761\U8457\U4e86";
direction = "\U5317\U4e0a";
happendate = "2017-02-09";
happentime = "01:08:00.0000000";
modDttm = "2017-02-09 01:15:43.603";
region = N;
road = "";
roadtype = "\U5176\U4ed6";
srcdetail = "\U71b1\U5fc3\U807d\U773e";
x1 = "121.73558";
y1 = "25.12263";
}
You need to call sort(by:) with a closure that determines the sort order. For example, if you want to sort by happendate and then happentime:
roadWayStatusArray.sort(by: { (lhsAny, rhsAny) -> Bool in
let lhs = lhsAny as? [String: AnyObject]
let rhs = lhsAny as? [String: AnyObject]
let lhsKey = (lhs?["happendate"] as? String ?? "", lhs?["happentime"] as? String ?? "")
let rhsKey = (rhs?["happendate"] as? String ?? "", rhs?["happentime"] as? String ?? "")
return lhsKey < rhsKey
})

how to get array from dictionary in swift 3

I don't understand how to get array from dictionary, i have tried in this code but i want get array only content and type
This is my array
{
wsResponse = {
aarti =(
{
content = "";
identifier = "slok_one";
title = 1;
type = "\U092d\U0915\U094d\U0924\U093e\U092e\U0930";
},
{
content = "";
identifier = "slok_two";
title = 2;
type = "\U092d\U0915\U094d\U0924\U093e\U092e\U0930";
},
{
content = "";
identifier = "slok_three";
title = 3;
type = "\U092d\U0915\U094d\U0924\U093e\U092e\U0930";
}
}
);
};
Here is my code
Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default)
.responseJSON { response in
if let status = response.response?.statusCode {
switch(status){
case 201:
print("example success")
default:
print("error with response status: \(status)")
}
}
//to get JSON return value
if let array = response.result.value
{
let JSON = array as! NSDictionary
print("\(JSON)")
let response = JSON["wsResponse"] as! NSDictionary
let data = response["aarti"]
}
}
i want array from this ,like content,title,type
thank you in advance
According to the JSON this prints all values in the aarti array:
if let JSON = response.result.value as? [String:Any] {
if let response = JSON["wsResponse"] as? [String:Any],
let aarti = response["aarti"] as? [[String:Any]] {
for item in aarti {
let content = item["content"] as! String
let identifier = item["identifier"] as! String
let title = item["title"] as! Int
let type = item["type"] as! String
print(content, identifier, title, type)
}
}
}
Basically do not use NSDictionary / NSArray in Swift.
If you want to put all content values in an array use flatMap. The line can replace the whole repeat loop.
let contentArray = aarti.flatMap { $0["content"] as? String }
PS: If you are going to create multiple arrays from the values don't do that: Use a custom struct or class
if someone want to get dictionary of array and use it in tableview
declaration:
var list:[Any] = []
and initialisation :
self.list = (self.ListDic?["data"] as! NSArray!) as! [Any]
and use:
let dictObj = self.list[indexPath.row] as! NSDictionary
print("object value: ",dictObj["text"] as! String)

Resources