appending JSON data? - ios

I want to append my JSON data for sending to server..
I have this code
var json = JSONSerializer.toJson(data2)
and this is my data2
var data2 = Activitiesdata (type: leftlabel.text!, amount: qtytext.text.toInt()!)
and this is my Activitiesdata
class Activitiesdata
{
var type = "type"
var amount = 0
init (type: String, amount: Int)
{
self.type = type
self.amount = amount
}
}
when I click on a icon (lets say softball) and I println the outcome like this
{"type": "Softball", "amount": 90}
but whenever I click another icon, the outcome like this
{"type": "Badminton", "amount": 60}
how to append the data? so that the outcome like this whenever I click the second button and so on..
{"type": "Softball", "amount": 90} {"type": "Badminton", "amount": 60}
or is it possible to make like this
{"type": "Softball", "amount": 90, "type": "Badminton", "amount": 60} // (only 1 bracket)
thanks
using array is a good idea, but I always get compile error .. please help thanks

You put not enough information to answer, but it looks like you create json object every time you press the button, that's why the old value in a variable var json is replaced by a new one. You must first create an array of the objects and then serialize it into json.
Your JSON result will looks somthing like this:
{[{"type": "Softball", "amount": 90}, {"type": "Badminton", "amount": 60}]}
I do not know what mechanism you use to serializing, but if it write in the style in which it is written in your code, it will be something like this:
var dataArray: [Activitiesdata] = []
// click on a icon
let firstElement = Activitiesdata (type: leftlabel.text!, amount: qtytext.text.toInt()!)
dataArray.append(firstElement)
// click another icon
let secondElement = Activitiesdata (type: otherlabel.text!, amount: otherText.text.toInt()!)
dataArray.append(secondElement)
// serialize array to json in your style
var json = JSONSerializer.toJson(dataArray)
There is a good library for working with JSON - https://github.com/SwiftyJSON/SwiftyJSON

Related

Swift - Update an array of NSDictionary with values from another NSDictionary

Basically, I have an NSarray of dictionaries coming as a JSON response only once when view appears. Now, I need to update a particular value of a key in those dictionaries with another set of dictionary coming separately in every few second such that I can update my array of dictionaries continuously with those values and show some realtime set of data on the screen.
Example: This is the array of dictionary I am getting from backend
[
{item_id: 1001, name: "Apple", current_price: "$10"},
{item_id: 1009, name: "Orange", current_price: "$15"},
{item_id: 1004, name: "Mango", current_price: "$5"}
]
Current price is something which varies continuously, whose data I am receiving in NSDictionary format separately.
["1009": "$16", "1004": "$3", "1001": "$11"]
As you can see the new NSDictionary is mapped with the item_id to the current price value.
I need a way out to make sure the current price gets updated from this NSDictionary to the array of dictionary so that I can reuse that array to reload my UITableview and show the updated realtime price.
You can do it like this:
let items = [["item_id": 1001, "name": "Apple", "current_price": "$10"], ["item_id": 1009, "name": "Orange", "current_price": "$15"], ["item_id": 1004, "name": "Mango", "current_price": "$5"]]
let prices = ["1009": "$16", "1004": "$3", "1001": "$11"]
let updatedItems = items.map { itemDict -> [String: Any] in
var updatedItem = itemDict
if let idKey = itemDict["item_id"] as? Int {
prices["\(idKey)"].flatMap { updatedItem["current_price"] = $0 }
}
return updatedItem
}

JSON data divided by using segmented control

I have some JSON data. The data is like below and I took a segmented control which contains active state and pending state, by using segmented control separate the JSON data. If order_status = 0 (below JSON data) that will store in pending state, if order_status = 1 that will store in active state.
I know how to parse JSON but I do not know how to separate the data by using segmented control.
{
"status": "done",
"order_data": [{
"price": "1000",
"qty": "1",
"total_price": "1000",
"voucher_id": "NIL",
"purchase_id": "1005",
"purchase_on": "NIL",
"validity": "30 days from the date of purchase",
"left_day": "NIL",
"order_status": 0
}, {
"price": "3000",
"qty": "1",
"total_price": "3000",
"voucher_id": "NIL",
"purchase_id": "10070",
"purchase_on": "NIL",
"validity": "30 days from the date of purchase",
"left_day": "NIL",
"order_status": 1
}, {
"price": "3000",
"qty": "1",
"total_price": "3000",
"voucher_id": "NIL",
"purchase_id": "1076767",
"purchase_on": "NIL",
"validity": "30 days from the date of purchase",
"left_day": "NIL",
"order_status": 1
}]
}
Let suppose that your data is in a variable named as jsonData, then firstly parse the json data and get two array of dictionary, one for pending state data and another one for active state data, then use both of the dictionary for segment control.
if let orderData = jsonData["order_data"] as? [[String:Any]] {
let pendingStateData = orderData.filter({ (newOrder) -> Bool in
return (newOrder["order_status"] as? Int) == 0
})
let activeStateData = orderData.filter({ (newOrder) -> Bool in
return (newOrder["order_status"] as? Int) == 1
})
}
So, using these filter you can filter the data and can get the desired filter data according to you.

SwiftyJSON how to append data

I try to create JSON with this structure:
var json: JSON = [
"params": [
"token": Utilities.token,
"language": "RU",
"billerId": biller.id,
],
"data": [
"serviceData": [
//I want put here additional data
]
]
]
in "serviceData" I want to add fields and values, but I don't know how much them and what is his name before compiling.
I try add this fields by this way:
for item in templateItems{
let key:String = item.name
let value: String = item.value
json["data"]["serviceData"][key] = value
}
according to https://github.com/SwiftyJSON/SwiftyJSON/tree/a1356035d2de68c155d05521292f0609ef7e69bb#literal-convertibles
but it doesn't work
It shouldn't be array, it is key-value dictionary.
Replace
"seviceData": []
With
"serviceData": [:]
The former defines an empty array. The latter defines an empty dictionary.

Parsing JSON with unknown root element in Swift with swiftlyJSON

I am working in iOS using Swift. The service I am using returns the following JSON (cut off as the node begins to repeat):
{
"Ambler Departures: April 15, 2015, 2:57 pm": [
{
"Northbound": [
{
"direction": "N",
"path": "R5N",
"train_id": "564",
"origin": "Frazer Yard",
"destination": "Colmar-Link Belt",
"status": "On Time",
"service_type": "LOCAL",
"next_station": "North Broad St",
"sched_time": "Apr 15 2015 03:27:00:000PM",
"depart_time": "Apr 15 2015 03:27:00:000PM",
"track": "2",
"track_change": null,
"platform": " ",
"platform_change": null
},
{
"direction": "N",
"path": "R5N",
"train_id": "6566",
"origin": null,
Notice that the root node is created dynamically by the service-- I don't have a way of knowing what it will be as the user can chose departures from one of fifty stations and the time is based on the time on the server, which is likely inconsistent with the time on the user's clock.
I want to extract the data from the Northbound Array, and then a Southbound Array lower in the JSON.
I am getting the data returned form the service but I can't parse correctly. I can't get past the root node (the dynamic one) to get to the structure inside.
Here's what I am trying:
let json = JSON(data:data)
var x = 0
while x < json.count
{
let track = json[0]["Northbound"][x]["track"].string
println(track)
x++
}
This results in "nil". I am stuck...
I know that json[0] is probably wrong since that level of the JSON is not an array. Thanks in advance
If json is a JSON object from SwiftyJSON but you know it's a dictionary with an unknown key, you can find this key with:
let theKey = json.dictionary!.keys.first
Then access the array:
let theArray = json[theKey] as! [[String:AnyObject]] // array of dictionaries
Then theArray[0] will be the dictionary with "Northbound" as a key, which contains an array of dictionaries containing the infos.
(Edited to reflect the correct answer specific to SwiftyJSON.)

json parsing in swift

Here is my Json
{
"id": "63",
"name": "Magnet",
"price": "₹1250",
"description": "",
"image": [
"catalog/IMG-20150119-WA0012_azw1e3ge.jpg",
"catalog/IMG-20150119-WA0029_6mr3ndda.jpg",
"catalog/IMG-20150119-WA0028_ooc2ea52.jpg",
"catalog/IMG-20150119-WA0026_4wjz5882.jpg",
"catalog/IMG-20150119-WA0024_e38xvczi.jpg",
"catalog/IMG-20150119-WA0020_vyzhfkvf.jpg",
"catalog/IMG-20150119-WA0018_u686bmde.jpg",
"catalog/IMG-20150119-WA0016_c8ffp19i.jpg"
],
"thumb_image": [
"cache/catalog/IMG-20150119-WA0012_azw1e3ge-300x412.jpg",
"cache/catalog/IMG-20150119-WA0029_6mr3ndda-300x412.jpg",
"cache/catalog/IMG-20150119-WA0028_ooc2ea52-300x412.jpg",
"cache/catalog/IMG-20150119-WA0026_4wjz5882-300x412.jpg",
"cache/catalog/IMG-20150119-WA0024_e38xvczi-300x412.jpg",
"cache/catalog/IMG-20150119-WA0020_vyzhfkvf-300x412.jpg",
"cache/catalog/IMG-20150119-WA0018_u686bmde-300x412.jpg",
"cache/catalog/IMG-20150119-WA0016_c8ffp19i-300x412.jpg"
],
"specifications": [
{
"Fabrics": [
"Pure chiffon straight cut suits 48" length"
]
},
{
"MOQ": [
"Minimum 10"
]
}
]
}
In above json string the "specification" arraylist has dynamic number of key and each key has dynamic number of values
So how can parse this? Please help if anyone knows this...
Thanks in advance
There are multiple ways to do parsing. In your case specifications should be an array, so you'll be able to loop on each items.
You might want to :
Create your own JSON parse class / methods ;
Use an existing library to parse JSON.
For the second option, you can give a look at the following :
https://github.com/Wolg/awesome-swift#jsonxml-manipulation
var yourJson = data as? NSDictionary
if let id = yourJson.valueForKey("id") as String
{
//save your id from json
}
if let name = yourJson.valueForKey("name") as String
{
//save your name
}
...
if let images = yourJson.valueForKey("image") as NSArray
{
for im in images
{
//save image
}
//the same for all othe images
}
... And so on...
You should also watch some tutorials, to understand the basics of JSON parsing..
https://www.youtube.com/watch?v=MtcscjMxxq4

Resources