having difficulty fetching JSON Dictionary - json

My response from API is
items are.....****************** ("user_img", http://www.xxx/Content/Images/Products/NoImageAvailable.jpg)
items are.....****************** ("user_posts", 10)
items are.....****************** ("5", {
"post_id" : 135,
"post_img" : [
{
"guid" : "http:\/\/www.xxx\/wp- content\/uploads\/2016\/10\/IMG_1477393867.jpg"
}
]
})
items are.....****************** ("9", {
"post_id" : 143,
"post_img" : [
{
"guid" : "http:\/\/www.xxx\/wp-content\/uploads\/2016\/10\/IMG_1477453054.jpg"
}
]
})
items are.....****************** ("2", {
"post_id" : 129,
"post_img" : [
{
"guid" : "http:\/\/www.xxx\/wp- content\/uploads\/2016\/10\/IMG_1477280037.jpg"
}
]
})
items are.....****************** ("1", {
"post_id" : 112,
"post_img" : [
{
"guid" : "http:\/\/www.xxx\/wp-content\/uploads\/2016\/10\/IMG_1475494067.jpg"
}
]
})
items are.....****************** ("8", {
"post_id" : 141,
"post_img" : [
{
"guid" : "http:\/\/www.xxx\/wp- content\/uploads\/2016\/10\/IMG_1477452361.jpg"
}
]
})
function from where I called it
func getJSON(){
let getEndPoint: String = "http://xxx/api/get_user_profile_info/"
Alamofire.request(getEndPoint)
.responseJSON { response in
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print("error calling GET")
print(response.result.error!)
return
}
if let value = response.result.value {
let json = JSON(value)
// print(jsonM)
//print("message are***********************************************")
//print(json["message"].dictionary)
let message = json["message"].dictionary
for items in message! {
print("items are.....******************", items)
}
//DispatchQueue.main.async {
// self.afData = 1
// self.tableView.reloadData()
}
}
}
Model Class
class ProfileJSON {
var user_Image: URL?
var post_image:URL?
init(items: JSON) {
self.user_Image = items["user_img"].URL
let post_imgAA = items["post_img"].array
for itemsIMG in post_imgAA! {
self.post_image = itemsIMG["guid"].URL
}
}
}
I want to get the user_img to show as profile picture and the
post_img for showing picture in the CollectionViewCell . Finding it difficult to convert JSON Dictionary to Swift MutableObject . Any suggestion , any tutorial link would be great great help for me. I have just started to work with JSON from this month , finding it difficult.

In your ProfileJSON you need to create array of URL type for post_image because user_Image is once but post_image is coming multiple times and then you can get post_image from dictionary like this.
class ProfileJSON {
var user_Image: URL?
var post_image: [URL?] = [URL?]()
init(dic: [String: Any]) {
if let userUrl = dic["user_img"] as? String {
self.user_Image = URL(string: userUrl)
}
//For getting only number keys with ascending order
let keys = (Array(dic.keys) as [String]).filter { (Int($0) != nil) }.sorted {
(s1, s2) -> Bool in return s1.localizedStandardCompare(s2) == .orderedAscending
}
//Loop through the keys Array and append all your `post_image`.
for key in keys {
if let innerDic = dic[key] as? [String: Any],
let post_imgArray = innerDic["post_img"] as? [[String: Any]] {
for post in post_imgArray {
if let postUrl = post["guid"] as? String {
self.post_image.append(URL(string: postUrl))
}
}
}
}
}
}
Now create the object of ProfileJSON after initialization of message like this.
if let message = json["message"] as? [String: Any] {
let profileJSON = ProfileJSON(dic: message)
}

You can extract details from dictionary using DicitonaryObject.objectForKey("KEYNAME") as? Datatype .
Datatype would the of the value stored in that key.
Store it in a variable and use it wherever you want.

Related

Swift 4 Json Parse

I need to throw this json data into the "arrayCategory" array above. How can I do it ?
"Elektronik" and "Hobi" titles are not fixed. It is variable.
Json Data
{
"Elektronik": [
{
"kategoriisim": "Akıllı Saatler",
"uyevarmi": "1"
},
{
"kategoriisim": "Anakart",
"uyevarmi": "1"
} ],
"Hobi": [
{
"kategoriisim": "Drone Multikopter",
"uyevarmi": "1"
}
]
}
Struct and Array . I need to fill in the "dimensionalArray" array
ExpandableNames "baslik" = The future of "Elektronik" data in json data
ExpandableNames "kategori" = The sub-elements of the "Elektronik" circuit will come
struct ExpandableNames {
let baslik : String
let kategori: [cellKategorilerData]
}
struct cellKategorilerData {
var kategoriisim : String?
var uyevarmi : String?
}
var dimensionalArray = [ExpandableNames]()
var arrayKategoriData = [cellKategorilerData]()
-
static func jsonSonucGetir(servlet:String,parametre:String) {
let connectString = Connect.ConnectInfo
var request = URLRequest(url: URL(string:connectString.conString + "/" + servlet)!)
request.httpMethod = "POST"
var postString = parametre
postString = postString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil
{
print("error" , error)
}
if let urlContent = data
{
do
{
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
???
}
catch
{
print("server hatasi")
}
}
}
task.resume()
}
If the keys are dynamic I recommend to decode the object as dictionary ([String:[CellKategorilerData]])
let jsonString = """
{
"Elektronik": [
{"kategoriisim": "Akıllı Saatler", "uyevarmi": "1"},
{"kategoriisim": "Anakart", "uyevarmi": "1"}
],
"Hobi": [
{"kategoriisim": "Drone Multikopter", "uyevarmi": "1"}
]
}
"""
struct CellKategorilerData : Decodable {
let kategoriisim : String
let uyevarmi : String
}
do {
let data = Data(jsonString.utf8)
let result = try JSONDecoder().decode([String:[CellKategorilerData]].self, from: data)
for (key, value) in result {
print("key", key, "value", value)
}
} catch { print(error) }

how to do safe json parsing in swift?

I am getting a Json of images from sever i have created one modal class & under which i have declared images as member of that class.
class SomeClass: NSObject {
var objImages:[Images] = [Images]()
}
Images as class
class Images {
var thumbImage:String = ""
var fullImage:String = ""
init(dictionary:NSDictionary){
fullImage = dictionary["thumb"] as? String ?? ""
thumbImage = dictionary["full_url"] as? String ?? ""
}
init() {
}
}
Parsing the json data
if let arrImg = dictionary["images"] {
for value in arrImg as! NSArray {
let tempImage:Images = Images(dictionary: value as! NSDictionary)
recipeImages.append(tempImage)
}
}
below is the josn response
{ "images": [
{
"thumb": "https://mysevrer.com/v0/b/a.png”,
"full_url": "https://mysevrer.com/v0/b/b.png"
},
{
"thumb": "https://mysevrer.com/v0/b/a.png”",
"full_url": "https://mysevrer.com/v0/b/b.png”"
}
]
}
Please is it safe way to parse response ?
What if i don'tget image as array
What if i don't get the "thumb"
& "full" as keys
I'm not sure if this is what you mean, but this will return an optional instance of Images. So it will return nil if the dictionary doesn't contain one or both of those keys.
class Images {
var thumbImage:String
var fullImage:String
init?(dictionary:Dictionary<String,String>){
guard let image = dictionary["thumb"] else { return nil }
guard let thumb = dictionary["full_url"] else { return nil }
self.fullImage = image
self.thumbImage = thumb
}
}
For the parsing part of the array.
guard let imagesArray = dictionary["images"] as? Array<Dictionary<String,String>> else { return }
for dict in imagesArray {
guard let images = Images(dictionary: dict) else { continue }
recipeImages.append(images)
}

Unable to parse json using alamofire using closures

Currently learning Swift and I'm new to parsing of json.
I'm trying to parse json using alamofire using swift 3. However Im not getting any response. How should I get the value of parameter1 or parameter 2 which were nested?
My json looks like this:
{ "data":{
"level1":{
"level2":{
"parameter1":"000000",
"parameter2":"00/00/00 00:00:00",
"parameter3":"00.0",
}
My swift code looks like this ,
func downloadDataDetails(completed: #escaping DownloadComplete) {
//Get data from URL
Alamofire.request("MY_URL").responseJSON { response in
let result = response.result
if let dict = result.value as? Dictionary<String , AnyObject> {
if let data = dict["data"] as? String {
if let level1 = dict["level1"] as? String {
if let level2 = dict["level2"] as? String? {
self._myValue = level2
}
}
}
}
completed()
}
I recommend you that use SwiftJson (https://cocoapods.org/pods/SwiftyJSON)
if you need to validate that something exist you can use .exist() (Return a boolean)
func test() {
let json: JSON = [ "data":[
"level1":[
"level2":[
"parameter1":"000000",
"parameter2":"00/00/00 00:00:00",
"parameter3":"00.0"
]
]
]
]
print(json) //Create a breakpoint here
}
If you have this JSON and you need to know if parameter1 exist:
(Put a break point in print(json))
(In the Console)
(lldb) po json["data"]["level1"]["level2"]["parameter1"].exists()
// response true
In the code would be:
if json["data"]["level1"]["level2"]["parameter1"].exists(){
}
If you need to get the value would be:
if json["data"]["level1"]["level2"]["parameter1"].exists(){
let parameter1 = json["data"]["level1"]["level2"]["parameter1"]
print(parameter1)
}
Complete example:
func test() {
let json: JSON = [ "data":[
"level1":[
"level2":[
"parameter1":"000000",
"parameter2":"00/00/00 00:00:00",
"parameter3":"00.0"
]
]
]
]
if json["data"]["level1"]["level2"]["parameter1"].exists(){
let parameter1 = json["data"]["level1"]["level2"]["parameter1"]
print(parameter1)
}
print(json["parameter1"])
}
The console log is:
000000
{
"data" : {
"level1" : {
"level2" : {
"parameter1" : "000000",
"parameter3" : "00.0",
"parameter2" : "00\/00\/00 00:00:00"
}
}
}
}

Get data from complex JSON in swift

I have a complex JSON data.
How can I parse this data?
I've tried, but it does not work.
I need a Dictionary with object (id, time...). But how to get through "1,.."?
And how can I take time begin and end?
"data": {
"1":[
{"id":6524612,
...
"time":{
"begin":"18:50",
"end":"19:20"
},
...
},
"2":[
{
"id":6524613,
...
"time":{
"begin":"18:50",
"end":"19:20"
},
...
},
Where is my mistake?
let broadcastTask = broadcastSession.dataTaskWithRequest(broadcastRequest) { (data, response, error) -> Void in
if error != nil {
print(error.debugDescription)
} else {
do {
let broadcastDict = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as? Dictionary<String, AnyObject>
if let results = broadcastDict!["data"] as? [Dictionary<String, AnyObject>] {
for obj in results {
let broadcast = Broadcast(broadcastDict: obj)
self.broadcastList.append(broadcast)
}
//Main UI thread
dispatch_async(dispatch_get_main_queue()) {
self.collectionView.reloadData()
}
}
} catch {
}
}
}
broadcastTask.resume()
init(broadcastDict: Dictionary<String, AnyObject>) {
if let category = broadcastDict["id"] as? Int {
self.id = id
}
...
}
If I understand the question correctly:
The first problem seems to be that you are trying to cast the "data" dictionary to an array of dictionaries. This will always fail because your data object is a dictionary and not an array.
Once you correct that problem you will run into trouble with your loop. Try this:
for (key, value) in results {
let broadcast = Broadcast(broadcastDict: value)
self.broadcastList.append(broadcast)
}
Now you are sending the dictionary that your Broadcast object is expecting.

Object At Index of Array with Value For Key

Does anyone know how to get the object at the index of an array, at the value for a specific key, and set it to a string?
I used to do this in Objective-C, but I can't quite figure out how to do it in Swift:
NSString *rT = [[self.rA objectAtIndex:0] valueForKey:#"Value"];
I've tried different things like this, but they don't work:
if let JSON = response.result.value {
print("JSON: \(JSON)")
var name: String? = self.rA[0].valueForKey("item_1") as? String
}
Endpoint:
[
{
"item_1": "Austin",
"item_2": "Texas"
}
]
Logging:
2016-04-01 13:35:42.787 A[66185:7391524] Response Array: (
{
"item_1" = Austin;
"item_2" = Texas;
}
)
I assume that you have something like array of dictionaries, So I made some test here it is sample code :
UPDATE
let jsonString = "[ { \"item_1\": \"Austin\", \"item_2\": \"Texas\" }, { \"item_3\": \"Austin3\", \"item_4\": \"Texas4\" } ]"
var array = []
do {
array = try NSJSONSerialization.JSONObjectWithData(jsonString.dataUsingEncoding(NSUTF8StringEncoding)!, options:.AllowFragments) as! NSArray
} catch {
print(error)
}
if let unwrappedValue = (array[0]["item_1"]){
print(unwrappedValue)
}
It will return an optional so it would be nice to use if let statement to unwrap value
For your usage this code should be like this :
if let JSON = response.result.value {
if let unwrappedValue = (JSON[0]["item_1"]){
print(unwrappedValue)
}
}