json date how to store in array - ios

data = "{\"2\":{\"Systolic_bp\":\"28\",\"Dystolic_bp\":\"29\",\"Weight\":\"22\",\"Height\":\"24\",\"Pulse\":\"26\",\"Temp\":\"25\",\"Respiration\":\"27\",\"BMI\":\"A:1:{s:4:\\\"SPO2\\\";s:1:\\\"1\\\";}\",\"BSA\":\"A:1:{s:4:\\\"SPO2\\\";s:1:\\\"1\\\";}\",\"tcomplients\":\"\",\"drdate\":\"25\\/08\\/2014\",\"medicine\":\"RABEPRAZOLE\",\"drugclass\":\"Tablet\",\"dosage\":\"1\",\"duration\":\"5 day\",\"frequency\":\"\",\"route\":\"Oral\",\"drnotes\":\"\"},\"1\":{\"tcomplients\":\"\",\"drdate\":\"25\\/08\\/2014\",\"medicine\":\"ACECLOFENAC+PARACETAMOL\",\"drugclass\":\"Tablet\",\"dosage\":\"1\",\"duration\":\"5 day\",\"frequency\":\"\",\"route\":\"Oral\",\"drnotes\":\"\"}}";
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
println(jsonData)
let dat1:NSString = jsonData.valueForKey("status")as NSString
let dat:NSString = jsonData.valueForKey("data") as NSString
if(dat1 == "SUCCESS")
{
// NSLog("Success: %d", jsonData);
var fullName: String = dat
// NSLog(fullName)
//firstName = "vinod"
let fullNameArr = fullName.componentsSeparatedByString(":")
//NSLog(fullName)
firstName = fullNameArr[0]
lastName = fullNameArr[1]
sex = fullNameArr[2]
Dob = fullNameArr[3]
encounter = fullNameArr[4]
consultDR = fullNameArr[5]
// room = fullNameArr[6]
//bed = fullNameArr[7]
//doa = fullNameArr[8]
//wardno = fullNameArr[9]
NSLog(fullNameArr[0])
NSLog(fullNameArr[1])
NSLog(fullNameArr[2])
NSLog(fullNameArr[3])
NSLog(fullNameArr[4])
NSLog(fullNameArr[5])
// NSLog(fullNameArr[6])
// NSLog(fullNameArr[7])
// NSLog(fullNameArr[8])
//NSLog(fullNameArr[9])
tried this not working

let jsonString = "{\"2\":{\"Systolic_bp\":\"28\",\"Dystolic_bp\":\"29\",\"Weight\":\"22\",\"Height\":\"24\",\"Pulse\":\"26\",\"Temp\":\"25\",\"Respiration\":\"27\",\"BMI\":\"A:1:{s:4:\\\"SPO2\\\";s:1:\\\"1\\\";}\",\"BSA\":\"A:1:{s:4:\\\"SPO2\\\";s:1:\\\"1\\\";}\",\"tcomplients\":\"\",\"drdate\":\"25\\/08\\/2014\",\"medicine\":\"RABEPRAZOLE\",\"drugclass\":\"Tablet\",\"dosage\":\"1\",\"duration\":\"5 day\",\"frequency\":\"\",\"route\":\"Oral\",\"drnotes\":\"\"},\"1\":{\"tcomplients\":\"\",\"drdate\":\"25\\/08\\/2014\",\"medicine\":\"ACECLOFENAC+PARACETAMOL\",\"drugclass\":\"Tablet\",\"dosage\":\"1\",\"duration\":\"5 day\",\"frequency\":\"\",\"route\":\"Oral\",\"drnotes\":\"\"}}"
if let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
var error: NSError?
if let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as? [String:AnyObject] {
let dicKeys = jsonDict.keys.array
for key in dicKeys {
println("\n")
if let subDic = jsonDict[key] as? [String:String] {
let subDicKeys = subDic.keys.array
for sKey in subDicKeys {
println(sKey + " = " + subDic[sKey]! )
}
}
}
} else {
println(false)
}
} else {
println(false)
}

Related

I am unable to get the child names from given url in swift 3?

In the api am getting global array but in this I am unable to get the children names as separate array only the last loaded array name has been getting in the array how to get the all children names in the array please help me how to get all the names in it and here is my code already tried
var detailsArray = NSArray()
var globalArray = NSMutableArray()
let url = "http://www.json-generator.com/api/json/get/cwqUAMjKGa?indent=2"
func downloadJsonWithURL() {
let url = NSURL(string: self.url)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
{
self.detailsArray = (jsonObj?.value(forKey: "data") as? [[String: AnyObject]])! as NSArray
print(self.detailsArray)
for item in self.detailsArray
{
let majorDic = NSMutableDictionary()
let detailDict = item as! NSDictionary
print(detailDict["name"]!)
majorDic .setValue(detailDict["name"]!, forKey: "name")
print(detailDict["children"]!)
if !(detailDict["children"]! is NSNull)
{
let children = detailDict["children"]! as! NSArray
let childrenstring = NSMutableString()
if children.count > 0 {
for item in children{
let chilDic = item as! NSDictionary
print(chilDic["name"]!)
print(chilDic["products"]!)
majorDic.setValue(chilDic["name"]!, forKey: "Childernname")
let products = chilDic["products"]! as! NSArray
if products.count > 0
{
for item in products
{
var sr = String()
sr = (item as AnyObject) .value(forKey: "name") as! String
childrenstring.append(sr)
childrenstring.append("*")
}
majorDic.setValue(childrenstring, forKey: "Childernproducts")
}
else
{
print("products.count\(products.count)")
majorDic.setValue("NO DATA", forKey: "Childernproducts")
}
}
}
else
{
print("childernw.count\(children.count)")
majorDic.setValue("NO DATA", forKey: "Childernname")
}
}
else
{
majorDic.setValue("NO DATA", forKey: "Childernname")
majorDic.setValue("NO DATA", forKey: "Childernproducts")
}
self.globalArray.add(majorDic)
}
print("TOTAL ASSECTS\(self.globalArray)")
OperationQueue.main.addOperation({
self.tableView.reloadData()
print(self.globalArray)
print(self.detailsArray)
})
}
}).resume()
}
Try this:
var detailsArray = [DataList]()
func downloadJsonWithURL() {
let url = NSURL(string: "http://www.json-generator.com/api/json/get/cwqUAMjKGa?indent=2")
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
{
let objArr = (jsonObj?["data"] as? [[String: AnyObject]])! as NSArray
for obj in objArr {
self.detailsArray.append(DataList(json: obj as! [String : AnyObject]))
}
print(self.detailsArray)
}
}).resume()
}
Model Class
class DataList: NSObject {
var count: Int
var category_id: Int
var childern:[Children]
var name:String
init (json: [String: AnyObject]){
if let childrenList = json["children"] as? [[String: AnyObject]] {
var result = [Children]()
for obj in childrenList {
result.append(Children(json: obj))
}
self.childern = result
} else {
self.childern = [Children]()
}
if let count = json["count"] as? Int { self.count = count }
else { self.count = 0 }
if let category_id = json["category_id"] as? Int { self.category_id = category_id }
else { self.category_id = 0 }
if let name = json["name"] as? String { self.name = name }
else { self.name = "" }
}
}
class Children:NSObject{
var count:Int
var category_id:Int
var products:[Products]
var name:String
init (json: [String: AnyObject]){
if let productList = json["products"] as? [[String: AnyObject]] {
var result = [Products]()
for obj in productList {
result.append(Products(json: obj))
}
self.products = result
} else {
self.products = [Products]()
}
if let count = json["count"] as? Int { self.count = count }
else { self.count = 0 }
if let category_id = json["category_id"] as? Int { self.category_id = category_id }
else { self.category_id = 0 }
if let name = json["name"] as? String { self.name = name }
else { self.name = "" }
}
}
class Products:NSObject{
var product_id:Int
var name:String
init (json: [String: AnyObject]){
if let product_id = json["product_id"] as? Int { self.product_id = product_id }
else { self.product_id = 0 }
if let name = json["name"] as? String { self.name = name }
else { self.name = "" }
}
}
NOTE: Please check your data type while parsing
I too had the same problem. Instead of using for loop try using flatMap() and then extract the value using value(forKey: " ") function
let productNames = productValues.flatMap() {$0.value}
let names = (productNames as AnyObject).value(forKey: "name")
It had worked for me for my json. My Json was similar to yours.
I got separate values in array.

Adding data to a particular table in CoreData in iOS Swift

I am using CoreData in my project and I am successfully able to save data in my tables and display. I am also able to update the existing Data. but I am not able to add a new data to a particular table.
The table relation is WorkOrderData--> one to many with WorkOrderTaskAsset and WorkOrderTaskAsset --> one to many with condition.
If I have to add a condition Object on some button click. I am not getting how to add it. I tried to create a Condition Object and add it. But I am getting error
.Condition setLabel:]: unrecognized selector sent to instance 0x600000077540'
func saveDataInCoreData(jsonArray : NSArray) {
for orders in jsonArray{
let WorkOrderDataClassName:String = String(describing: WorkOrderData.self)
let workOrderData:WorkOrderData = NSEntityDescription.insertNewObject(forEntityName: WorkOrderDataClassName, into: DatabaseController.getContext()) as! WorkOrderData
let ContractorClassName:String = String(describing: Contractor.self)
let contractor:Contractor = NSEntityDescription.insertNewObject(forEntityName: ContractorClassName, into: DatabaseController.getContext()) as! Contractor
let StatusClassName:String = String(describing: Status.self)
let status:Status = NSEntityDescription.insertNewObject(forEntityName: StatusClassName, into: DatabaseController.getContext()) as! Status
let order = orders as! NSDictionary
// Work Order Parsing
workOrderData.workOrderNo = order["workOrderNo"]! as? String
if order["description"] != nil {
workOrderData.descriptin = order["description"]! as? String
}
if order["comments"] != nil {
workOrderData.comments = order["comments"]! as? String
}
let desCodeId = order["descriptionCodeID"]! as? Int
if desCodeId != nil {
workOrderData.descriptionCodeID = Int16(UInt16(desCodeId!))
}
if order["definition"] != nil {
workOrderData.definition = order["definition"]! as? String
}
let priortyID = order["priorityID"]! as? Int
if priortyID != nil {
workOrderData.priorityID = Int16(UInt16(desCodeId!))
}
let numbrOfAssets = order["numberofAssests"]! as? Int
if numbrOfAssets != nil {
workOrderData.numberofAssests = Int16(UInt16(numbrOfAssets!))
}
if order["generatedDateTime"] != nil {
workOrderData.generatedDateTime = (order["generatedDateTime"]! as? Double)!
}
if order["initiatedBy"] != nil {
workOrderData.initiatedBy = order["initiatedBy"]! as? String
}
if order["generatedBy"] != nil {
workOrderData.generatedBy = order["generatedBy"]! as? String
}
if order["issueDate"] != nil {
workOrderData.issueDate = (order["issueDate"]! as? Double)!
}
if order["finishDate"] != nil {
workOrderData.finishDate = (order["finishDate"]! as? Double)!
}
if order["statusID"] != nil {
let statsID = order["statusID"]! as? Int
workOrderData.statusID = Int16(UInt16(statsID!))
}
if order["assigneeID"] != nil {
let assigneID = order["assigneeID"]! as? Int
workOrderData.assigneeID = Int16(UInt16(assigneID!))
}
if order["updateDate"] != nil {
let updatDate = order["updateDate"]! as? Double
workOrderData.updateDate = updatDate!
}
if order["startDate"] != nil {
workOrderData.startDate = (order["startDate"]! as? Double)!
}
if order["proceedDate"] != nil {
workOrderData.proceedDate = (order["proceedDate"]! as? Double)!
}
if order["createDate"] != nil {
workOrderData.createDate = (order["createDate"]! as? Double)!
}
if order["inclementDays"] != nil {
let inclemntDays = order["inclementDays"]! as? Int
workOrderData.inclementDays = Int16(UInt16(inclemntDays!))
}
if order["totalHydrantsPainted"] != nil {
let totalHydrantPainted = order["totalHydrantsPainted"]! as? Int
workOrderData.totalHydrantsPainted = Int16(UInt16(totalHydrantPainted!))
}
if order["totalHydrantsNotPainted"] != nil {
let totalHydrantNotPainted = order["totalHydrantsNotPainted"]! as? Int
workOrderData.totalHydrantsNotPainted = Int16(UInt16(totalHydrantNotPainted!))
}
if order["contractorId"] != nil {
let contractrId = order["contractorId"]! as? Int
workOrderData.contractorId = Int16(UInt16(contractrId!))
}
// Contractor Started
let contractorDict = order["contractor"]! as? NSDictionary
if contractorDict?["id"] != nil {
let contrctrId = contractorDict?["id"]! as? Int
contractor.id = Int16(UInt16(contrctrId!))
}
contractor.name = contractorDict?["name"]! as? String
contractor.email = contractorDict?["email"]! as? String
contractor.label = contractorDict?["label"]! as? String
contractor.purchaseOrderNumber = contractorDict?["purchaseOrderNumber"]! as? String
contractor.vendorId = contractorDict?["vendorId"]! as? String
workOrderData.contractor = contractor
if order["status"] != nil {
let statusDict = order["status"]! as? NSDictionary
let statusId = statusDict?["id"]! as? Int
if statusId != nil {
status.id = Int16(UInt16(statusId!))
}
status.label = statusDict?["label"]! as? String
status.descriptin = statusDict?["description"]! as? String
status.rule = statusDict?["rule"]! as? String
workOrderData.status = status
}
// Inclement Work Order Started
if order["workOrderInclementWeatherDates"] != nil {
let workOrderInclementWeatherDate = order["workOrderInclementWeatherDates"] as! [NSDictionary]
if workOrderInclementWeatherDate.count > 0 {
let setArray = NSMutableArray()
let set = NSMutableSet()
for inclementItem in workOrderInclementWeatherDate {
let WorkOrderInclementWeatherDatesClassName:String = String(describing: WorkOrderInclementWeatherDates.self)
let workOrderInclementWeatherDates:WorkOrderInclementWeatherDates = NSEntityDescription.insertNewObject(forEntityName: WorkOrderInclementWeatherDatesClassName, into: DatabaseController.getContext()) as! WorkOrderInclementWeatherDates
workOrderInclementWeatherDates.createTimeStamp = inclementItem.value(forKey: "createTimeStamp") as! Double
workOrderInclementWeatherDates.inclementDate = inclementItem.value(forKey: "inclementDate") as! Double
workOrderInclementWeatherDates.workOrderNo = inclementItem.value(forKey: "workOrderNo") as? String
setArray.add(workOrderInclementWeatherDates)
set.add(workOrderInclementWeatherDates)
}
workOrderData.addToWorkOrderInclementWeather(set as NSSet)
}
}
// Task List
// Inclement Work Order Started
if order["workOrderTask"] != nil {
let workOrderTaskArray = order["workOrderTask"] as! [NSDictionary]
if workOrderTaskArray.count > 0 {
let workOrderSet = NSMutableSet()
for workOrderItem in workOrderTaskArray {
let WorkOrderTaskClassName:String = String(describing: WorkOrderTask.self)
let workOrderTask:WorkOrderTask = NSEntityDescription.insertNewObject(forEntityName: WorkOrderTaskClassName, into: DatabaseController.getContext()) as! WorkOrderTask
workOrderTask.woTaskDescription = workOrderItem.value(forKey: "woTaskDescription") as? String
workOrderTask.taskStatus = workOrderItem.value(forKey: "taskStatus") as? String
if workOrderItem["projectedStartDate"] != nil {
workOrderTask.projectedStartDate = workOrderItem.value(forKey: "projectedStartDate") as! Double
}
if workOrderItem["actualStartDate"] != nil {
workOrderTask.actualStartDate = workOrderItem.value(forKey: "actualStartDate") as! Double
}
if workOrderItem["taskNumber"] != nil {
let taskNumber = workOrderItem["taskNumber"]! as? Int
workOrderTask.taskNumber = Int16(UInt16(taskNumber!))
}
if workOrderItem["noOfHydrantsCompleted"] != nil {
let noOfHydrantsCompleted = workOrderItem["noOfHydrantsCompleted"]! as? Int
workOrderTask.noOfHydrantsCompleted = Int16(UInt16(noOfHydrantsCompleted!))
}
if workOrderItem["noOfHydrantsPending"] != nil {
let noOfHydrantsPending = workOrderItem["noOfHydrantsPending"]! as? Int
workOrderTask.noOfHydrantsPending = Int16(UInt16(noOfHydrantsPending!))
}
workOrderSet.add(workOrderTask)
}
workOrderData.addToWorkOrdertask(workOrderSet as NSSet)
}
}
// workOrderTaskAsstDetails
if order["workOrderTaskAsstDetails"] != nil {
let workOrderTaskAsstDetailsDict = order["workOrderTaskAsstDetails"] as! [NSDictionary]
if workOrderTaskAsstDetailsDict.count > 0 {
let set = NSMutableSet()
for workOrderTaskAsstDetailsItem in workOrderTaskAsstDetailsDict {
let WorkOrderTaskAsstDetailsClassName:String = String(describing: WorkOrderTaskAsstDetails.self)
let workOrderTaskAsstDetails:WorkOrderTaskAsstDetails = NSEntityDescription.insertNewObject(forEntityName: WorkOrderTaskAsstDetailsClassName, into: DatabaseController.getContext()) as! WorkOrderTaskAsstDetails
let woTaskAsstId = workOrderTaskAsstDetailsItem["woTaskAsstId"]! as? Int
if woTaskAsstId != nil {
workOrderTaskAsstDetails.woTaskAsstId = Int16(UInt16(woTaskAsstId!))
}
workOrderTaskAsstDetails.woTaskNo = workOrderTaskAsstDetailsItem.value(forKey: "woTaskNo") as? String
workOrderTaskAsstDetails.assetId = workOrderTaskAsstDetailsItem.value(forKey: "assetId") as? String
workOrderTaskAsstDetails.descripton = workOrderTaskAsstDetailsItem.value(forKey: "description") as? String
workOrderTaskAsstDetails.statusID = workOrderTaskAsstDetailsItem.value(forKey: "statusID") as? String
if workOrderTaskAsstDetailsItem["projectedStartDate"] != nil {
workOrderTaskAsstDetails.projectedStartDate = (workOrderTaskAsstDetailsItem["projectedStartDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["actualStartDate"] != nil {
workOrderTaskAsstDetails.actualStartDate = (workOrderTaskAsstDetailsItem["actualStartDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["projectedCompleteDate"] != nil {
workOrderTaskAsstDetails.projectedCompleteDate = (workOrderTaskAsstDetailsItem["projectedCompleteDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["actualCompleteDate"] != nil {
workOrderTaskAsstDetails.actualCompleteDate = (workOrderTaskAsstDetailsItem["actualCompleteDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["lastPaintedDate"] != nil {
workOrderTaskAsstDetails.lastPaintedDate = (workOrderTaskAsstDetailsItem["lastPaintedDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["workOrderStartDate"] != nil {
workOrderTaskAsstDetails.workOrderStartDate = (workOrderTaskAsstDetailsItem["workOrderStartDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["createDate"] != nil {
workOrderTaskAsstDetails.createDate = (workOrderTaskAsstDetailsItem["createDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["updateDate"] != nil {
workOrderTaskAsstDetails.updateDate = (workOrderTaskAsstDetailsItem["updateDate"]! as? Double)!
}
workOrderTaskAsstDetails.workOrderNumber = workOrderTaskAsstDetailsItem.value(forKey: "workOrderNumber") as? String
workOrderTaskAsstDetails.beforePicLatitude = workOrderTaskAsstDetailsItem.value(forKey: "beforePicLatitude") as? String
workOrderTaskAsstDetails.beforePicLongitude = workOrderTaskAsstDetailsItem.value(forKey: "beforePicLongitude") as? String
workOrderTaskAsstDetails.afterPicLatitude = workOrderTaskAsstDetailsItem.value(forKey: "afterPicLatitude") as? String
workOrderTaskAsstDetails.afterPicLongitude = workOrderTaskAsstDetailsItem.value(forKey: "afterPicLongitude") as? String
let transactionType = workOrderTaskAsstDetailsItem["transactionType"]! as? Int
if transactionType != nil {
workOrderTaskAsstDetails.transactionType = Int16(UInt16(transactionType!))
}
let assetValid = workOrderTaskAsstDetailsItem["assetValid"]! as? Int
if assetValid != nil {
workOrderTaskAsstDetails.assetValid = Int16(UInt16(assetValid!))
}
//Asset
let AssetClassName:String = String(describing: Asset.self)
let asset:Asset = NSEntityDescription.insertNewObject(forEntityName: AssetClassName, into: DatabaseController.getContext()) as! Asset
let assetDict = workOrderTaskAsstDetailsItem["asset"]! as? NSDictionary
asset.descripton = assetDict?["description"]! as? String
asset.type = assetDict?["type"]! as? String
asset.assetId = assetDict?["assetId"]! as? String
if assetDict?["asset200ft"] != nil {
asset.asset200ft = assetDict?["asset200ft"]! as? String
}
if assetDict?["streetNumber"] != nil{
asset.streetNumber = assetDict?["streetNumber"]! as? String
}
asset.county = assetDict?["county"]! as? String
asset.latitude = assetDict?["latitude"]! as? String
asset.longitude = assetDict?["longitude"]! as? String
workOrderTaskAsstDetails.asset = asset
//Condition
if workOrderTaskAsstDetailsItem["assetConditions"] != nil{
let conditionDict = workOrderTaskAsstDetailsItem["assetConditions"] as! [NSDictionary]
if conditionDict.count > 0{
let conditinSet = NSMutableSet()
for assetConditionsDetailsDict in conditionDict {
let ConditionClassName:String = String(describing: Condition.self)
let condition:Condition = NSEntityDescription.insertNewObject(forEntityName: ConditionClassName, into: DatabaseController.getContext()) as! Condition
let assetConditionItem = assetConditionsDetailsDict["condition"] as! NSDictionary
condition.id = assetConditionItem["id"]as? String
condition.label = assetConditionItem["label"]as? String
condition.rule = assetConditionItem["rule"]as? String
condition.descriptin = assetConditionItem["description"]as? String
conditinSet.add(condition)
}
workOrderTaskAsstDetails.addToCondition(conditinSet as NSSet)
}
}
set.add(workOrderTaskAsstDetails)
}
workOrderData.addToWorkOrderTaskAsstDetails(set as NSSet)
}
}
// assetList
if order["assetList"] != nil {
let workOrderTaskAsstDetailsDict = order["assetList"] as! [NSDictionary]
if workOrderTaskAsstDetailsDict.count > 0 {
let set = NSMutableSet()
for workOrderTaskAsstDetailsItem in workOrderTaskAsstDetailsDict {
let WorkOrderTaskAsstDetailsClassName:String = String(describing: AssetList.self)
let workOrderTaskAsstDetails:AssetList = NSEntityDescription.insertNewObject(forEntityName: WorkOrderTaskAsstDetailsClassName, into: DatabaseController.getContext()) as! AssetList
let woTaskAsstId = workOrderTaskAsstDetailsItem["woTaskAsstId"]! as? Int
if woTaskAsstId != nil {
workOrderTaskAsstDetails.woTaskAsstId = Int16(UInt16(woTaskAsstId!))
}
workOrderTaskAsstDetails.woTaskNo = workOrderTaskAsstDetailsItem.value(forKey: "woTaskNo") as? String
workOrderTaskAsstDetails.assetId = workOrderTaskAsstDetailsItem.value(forKey: "assetId") as? String
workOrderTaskAsstDetails.descripton = workOrderTaskAsstDetailsItem.value(forKey: "description") as? String
workOrderTaskAsstDetails.statusID = workOrderTaskAsstDetailsItem.value(forKey: "statusID") as? String
if workOrderTaskAsstDetailsItem["projectedStartDate"] != nil {
workOrderTaskAsstDetails.projectedStartDate = (workOrderTaskAsstDetailsItem["projectedStartDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["actualStartDate"] != nil {
workOrderTaskAsstDetails.actualStartDate = (workOrderTaskAsstDetailsItem["actualStartDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["projectedCompleteDate"] != nil {
workOrderTaskAsstDetails.projectedCompleteDate = (workOrderTaskAsstDetailsItem["projectedCompleteDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["actualCompleteDate"] != nil {
workOrderTaskAsstDetails.actualCompleteDate = (workOrderTaskAsstDetailsItem["actualCompleteDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["lastPaintedDate"] != nil {
workOrderTaskAsstDetails.lastPaintedDate = (workOrderTaskAsstDetailsItem["lastPaintedDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["workOrderStartDate"] != nil {
workOrderTaskAsstDetails.workOrderStartDate = (workOrderTaskAsstDetailsItem["workOrderStartDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["createDate"] != nil {
workOrderTaskAsstDetails.createDate = (workOrderTaskAsstDetailsItem["createDate"]! as? Double)!
}
if workOrderTaskAsstDetailsItem["updateDate"] != nil {
workOrderTaskAsstDetails.updateDate = (workOrderTaskAsstDetailsItem["updateDate"]! as? Double)!
}
workOrderTaskAsstDetails.workOrderNumber = workOrderTaskAsstDetailsItem.value(forKey: "workOrderNumber") as? String
workOrderTaskAsstDetails.beforePicLatitude = workOrderTaskAsstDetailsItem.value(forKey: "beforePicLatitude") as? String
workOrderTaskAsstDetails.beforePicLongitude = workOrderTaskAsstDetailsItem.value(forKey: "beforePicLongitude") as? String
workOrderTaskAsstDetails.afterPicLatitude = workOrderTaskAsstDetailsItem.value(forKey: "afterPicLatitude") as? String
workOrderTaskAsstDetails.afterPicLongitude = workOrderTaskAsstDetailsItem.value(forKey: "afterPicLongitude") as? String
let transactionType = workOrderTaskAsstDetailsItem["transactionType"]! as? Int
if transactionType != nil {
workOrderTaskAsstDetails.transactionType = Int16(UInt16(transactionType!))
}
let assetValid = workOrderTaskAsstDetailsItem["assetValid"]! as? Int
if assetValid != nil {
workOrderTaskAsstDetails.assetValid = Int16(UInt16(assetValid!))
}
//Asset
let AssetClassName:String = String(describing: AssetListAsset.self)
let asset:AssetListAsset = NSEntityDescription.insertNewObject(forEntityName: AssetClassName, into: DatabaseController.getContext()) as! AssetListAsset
let assetDict = workOrderTaskAsstDetailsItem["asset"]! as? NSDictionary
asset.descripton = assetDict?["description"]! as? String
asset.type = assetDict?["type"]! as? String
asset.assetId = assetDict?["assetId"]! as? String
if assetDict?["asset200ft"] != nil {
asset.asset200ft = assetDict?["asset200ft"]! as? String
}
if assetDict?["streetNumber"] != nil{
asset.streetNumber = assetDict?["streetNumber"]! as? String
}
asset.county = assetDict?["county"]! as? String
asset.latitude = assetDict?["latitude"]! as? String
asset.longitude = assetDict?["longitude"]! as? String
workOrderTaskAsstDetails.assetListAsset = asset
//Condition
if workOrderTaskAsstDetailsItem["assetConditions"] != nil{
let conditionDict = workOrderTaskAsstDetailsItem["assetConditions"] as! [NSDictionary]
if conditionDict.count > 0{
let conditinSet = NSMutableSet()
for assetConditionsDetailsDict in conditionDict {
let ConditionClassName:String = String(describing: AssetListCondition.self)
let condition:AssetListCondition = NSEntityDescription.insertNewObject(forEntityName: ConditionClassName, into: DatabaseController.getContext()) as! AssetListCondition
let assetConditionItem = assetConditionsDetailsDict["condition"] as! NSDictionary
condition.id = assetConditionItem["id"]as? String
condition.label = assetConditionItem["label"]as? String
condition.rule = assetConditionItem["rule"]as? String
condition.descriptin = assetConditionItem["description"]as? String
conditinSet.add(condition)
}
workOrderTaskAsstDetails.addToAssetListCondition(conditinSet as NSSet)
}
}
set.add(workOrderTaskAsstDetails)
}
workOrderData.addToAssetList(set as NSSet)
}
}
DatabaseController.saveContext()
}
fetchFrmDB()
}
the code include other table also which I have not shown in pic
Please help me.. Thanks in Advance

Trouble with JSON parsing in swift 1.2

Trouble with JSON parsing in swift 1.2
I have an issue with the JSON parsing, i am not getting the correct data response for my parameters. i have been stuck on the issue for quite some time now. i don’t know how to fix it. i am new to iOS development. also i haven’t used any third party library.[Don’t know how to use them]
I am getting the right response for my very first iteration but for the next iteration results of previous iteration is added along with the new results. Like that each loop result is ended up with the results of previous iteration
My JSON SAMPLE.[can provide link, please let me know]
struct AssetItems {
var Name:String
var Desc:String
var Image:String
var entityId:String
var aFileType:String
var aFileSize:String
var aFileCreatedDate:String
var aFileRevisionDate:String
var aFileModifiedDate:String
var aProductName:String
var aVersion:String
var aAssetType:String
var aIsFolder:String
init(assetName:String,assetDescription:String,assetImage:String,entityId:String,FileType:String,FileSize:String,FileCretedDate:String,FileReveisionDate:String,FileModifiedDate:String,ProductName:String,Version:String,AssetType:String,IsFolder:String) {
self.Name = assetName
self.Desc = assetDescription
self.Image = assetImage
self.entityId = entityId
self.aFileType = FileType
self.aFileSize = FileSize
self.aFileCreatedDate = FileCretedDate
self.aFileRevisionDate = FileReveisionDate
self.aFileModifiedDate = FileModifiedDate
self.aProductName = ProductName
self.aVersion = Version
self.aAssetType = AssetType
self.aIsFolder = IsFolder
}
}
struct AssetModel {
var aName:String
var aDesc:String
var aCount:String
var aEntityId:String
var items:[AssetItems]
init(rackName:String,rackDescription:String,totalNoAssets:String,EntityId:String,rackItems:[AssetItems]) {
self.aName = rackName
self.aDesc = rackDescription
self.aCount = totalNoAssets
self.aEntityId = EntityId
self.items = rackItems
}
}
var assetData:Array<AssetModel> = Array<AssetModel>()
var assetContents:Array<AssetItems> = Array<AssetItems>()
THIS IS HOW I AM PARSING JSON
func get_data_from_Url(url:String) {
let url = NSURL(string: url)
var request:NSMutableURLRequest = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content_Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var responseError : NSError?
var response : NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &responseError)
if(urlData != nil) {
var responseData:NSString = NSString(data: urlData!, encoding: NSUTF8StringEncoding)!
let res = response as! NSHTTPURLResponse
var err:NSError?
if (res.statusCode == 200)
{
var parseError: NSError?
let json:AnyObject = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &err) as AnyObject!
if (parseError == nil) // no error while parsing
{
if let Asset_list = json as? NSArray
{
for (var i = 0; i < Asset_list.count ; i++ )
{
if let Asset_obj = Asset_list[i] as? NSDictionary
{
if let AssetGroupName = Asset_obj["Name"] as? String
{
if let AssetGroupDescription = Asset_obj["Description"] as? String
{
if let entityId = Asset_obj["EntityId"] as? String
{
if let totalAssets = Asset_obj["_NoOfAssets"] as? String
{
if let items = Asset_obj["Items"] as? NSArray
{
for (var j=0 ; j < items.count; j++)
{
if let asset_items = items[j] as? NSDictionary
{
if let AbsolutePath = asset_items["AbsolutePath"] as? String
{
if let Description = asset_items["_Description"] as? String
{
if let Name = asset_items["_Name"] as? String {
if let entityId = asset_items["EntityId"] as? String
{
if let FileType = asset_items["_FileType"] as? String
{
if let FileSize = asset_items["_FileSize"] as? String
{
if let FileCreatedDate = asset_items["CreatedDate"] as? String
{
if let FileModifiedDate = asset_items["ModifiedDate"] as? String
{
if let RevisionDate = asset_items["RevisionDate"] as? String
{
if let productName = asset_items["ProductName"] as? String
{
if let version = asset_items["Version"] as? String
{
if let AssetType = asset_items["_AssetType"] as? String
{
if let isFolder = asset_items["IsFolder"] as? String
{
var add = AssetItems(assetName: Name, assetDescription: Description, assetImage: AbsolutePath, entityId: entityId, FileType: FileType, FileSize: FileSize, FileCretedDate: FileCreatedDate, FileReveisionDate: RevisionDate, FileModifiedDate: FileModifiedDate, ProductName: productName, Version: version, AssetType: AssetType, IsFolder: isFolder)
assetContents.append(add)
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
var add_it = AssetModel(rackName: AssetGroupName, rackDescription: AssetGroupDescription, totalNoAssets: totalAssets, EntityId: entityId, rackItems: assetContents)
assetData.append(add_it)
}
}
}
}
}
}
}
}
}
}
}
do_table_refresh()
}
func do_table_refresh()
{
dispatch_async(dispatch_get_main_queue(),
{
self.tableView.reloadData()
})
return
}
My Output
Please some one help me fix this, Any suggestion will also do.
THANKS
Special thanks to #SMi, With his GuidLines i was able to solve my issue.
I knew that i had to clear the inner array at the end of the loop[But,didn't knew how to clear that.]
var add_it = AssetModel(rackName: AssetGroupName, rackDescription: AssetGroupDescription, totalNoAssets: totalAssets, EntityId: entityId, rackItems: assetContents)
assetData.append(add_it)
assetContents.removeAll()
All i had to do is use the .removeAll() method to clear the assetContents Array.

how to extract a json object using swift?

JSON function:
func extract_json(data:NSString){
var parseError: NSError?
let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &parseError)
if (parseError == nil){
if let coupon_list = json as? [String: AnyObject]{
if let coupons = coupon_list["data"] as? [AnyObject]{
for (var i = 0; i < coupons.count ; i++ ){
if let coupon_obj = coupons[i] as? NSDictionary{
let location: AnyObject? = coupon_obj.objectForKey("location")
//the print the value location
println(location)
//I just want to get the number keys before the value of the location
this is my Json object where you can see that
{
brand = "Mang Inasal";
category = (
2
);
desc = "Mang Inasal Salmonella Giveaway";
discount = 50;
"end_date" = 1443369600;
id = 2;
imgs = (
"http://mymegamobile.com/savvy/halo2x.png",
"http://mymegamobile.com/savvy/bar_filter.png",
"http://mymegamobile.com/savvy/bar_mega.png",
"http://mymegamobile.com/savvy/box1.png",
"http://mymegamobile.com/savvy/box2.png"
);
location = {
1435307555 = Baguio;
};
name = "Mang Inasal Halo Halo";
stamp = "2015-09-02 14:04:38";
"start_date" = 1438012800;
}
the result of the object structure is above.
How can I get the value of 1435307555 in my location?
You can do it this way:
let yourObject = location?.objectForKey("165952298") as! String
for (key,value) in coupon_list {
println(key)
}
This way you'll get all keys from the JSON
func extract_json(data:NSString){
var parseError: NSError?
let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &parseError) as! NSDictionary
if (parseError == nil) {
for (var i = 0; i < json.count ; i++ ) {
let location: AnyObject? = ((json)["location"] as! NSDictionary)["1435307555"]
//the print the value location
println(location)
}
}

Append data to multidimensional array (swift)

I'm having a problem with passing data in an multidimensional array.
So this is the Array:
var dataHome:[[String]] = []
And I would like to pass data into it like this:
if let countries_list = json as? NSArray
{
for (var i = 0; i < countries_list.count ; i++ )
{
if let country_obj = countries_list[i] as? NSDictionary
{
println(country_obj)
let countryName = country_obj["country"] as! String
let countryCode = country_obj["code"] as! String
var tempArray:[String] = []
tempArray.append(countryName)
tempArray.append(countryCode)
println(tempArray)
dataHome.append(tempArray)
println(dataHome)
}
}
}
It crashes when I try to pass data into dataHome.append(tempArray)
The array from country_obj is {code = US;country = Amerika;}
Does anybody have an solution ?
Thank's !
EDIT:
the whole function is:
func extract_json(data:NSString){
var parseError: NSError?
let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &parseError)
if (parseError == nil)
{
if let countries_list = json as? NSArray
{
for (var i = 0; i < countries_list.count ; i++ )
{
if let country_obj = countries_list[i] as? NSDictionary
{
println(country_obj)
var countryName = country_obj["country"] as! String
var countryCode = country_obj["code"] as! String
println(countryName)
println(countryCode)
var tempArray:[String] = []
tempArray.append(countryName)
tempArray.append(countryCode)
println(tempArray)
dataHome.append(tempArray)
println(dataHome)
}
}
}
}
do_table_refresh();
}
The error is: Thread 3: Breakpoint 2.1
tempArray.append(countryName)

Resources