I use the Alamofire library this way:
Alamofire.request(.POST, "http://www.somesample.com/getData.php", parameters: ["user":"charles"]).responseJSON{jsonData in
var theData = jsonData.result.value
If I debug print the theData variable, it throws something like:
[
{
"userId" : "61",
"userPicture" : "147884767502.jpg",
"wasId" : "80",
"favorite" : "0",
"message" : "how are you?",
"username" : "paco",
"date" : "13\/10\/2015 03:44PM",
"userPhrase" : "hello"
"repliesNumber" : 2
},
{
"userId" : "3",
"userPicture" : "149181897286.jpg",
"wasId" : "5",
"favorite" : "0",
"message" : "let's go!",
"username" : "loliFlower",
"date" : "30\/08\/2015 07:48PM",
"userPhrase" : "ciiiii!",
"repliesNumber" : 3
}
]
I usually use SwiftyJSON so I write (even I use a for loop to walk to every single index of the array the SwiftyJSON makes:
var myData = JSON(theData.result.value)
print(myData[0]["username"].stringValue)
But what if I don't want to use SwiftyJSON library anymore? what is the native way to do this?
I recommend that you use code generation to create native models out of the json response, this will save your time of parsing by hand and reduce the risk of errors due to mistaken keys, all elements will be accessible by model properties, this will be purely native and the models will make more sense rather checking the keys. Check http://www.json4swift.com and let me know if you require further help in initiating the object from your json response. (make sure you enter the actual json response and not the printed object as that in your question)
Related
Hi all I am having a hard time saving coordinates in an array on Firebase. Basically I would like to track my location and save the Latitude and Longitude whenever there is a change in location.
This is what I currently get:
"-R359orfmkXiwERe948fk" : {
"coordinates" : {
"-S6O96394fXd0489fj" : {
"lat" : Lat1,
"long" : Long1
},
"-S6496SX235Hh12G893sb" : {
"lat" : lat2,
"long" : long2
},
"-F6O3941SwKZ5cA29038kdsg" : {
"lat" : lat3,
"long" : lat3
},
While This is the form I would like to get:
"-385fjAhm85fwERe948fk" : {
"coordinates" : [ [ Lat1,Long1], [Lat 2, Long2], [Lat 2, Long3]]
Using Firebase RealTime database and Swift 3
Firebase has no native support for arrays.
Instead of expecting Firebase to return you an array, I suggest writing a transformation method for your Swift model object, that you can use when you query Firebase, which converts the dictionary you currently receive into an array that you can then utilize throughout your app.
You will need a similar transformation that will then convert your array back to that dictionary format for updating Firebase.
I'm trying to make an app that will select an index at random, something like 0-1000 and then print the key, value, and link of the selected number to three seperate labels on the iPhone simulator.
So from my example, I want to randomly select "0" or "1" and if for instance "1" was chosen; then the key, value, and link information would each be printed to three separate labels on the simulator. The following is what I've been working on in playgrounds. Is there a better way to go about this?
var spDictionary: [String: [String:String]] = [
"0": ["key": "AMZN", "value": "AMAZON", "link": "yahoo"],
"1": ["key": "AAPL", "value": "APPLE", "link": "yahoo2"],
]
And for the random aspect I think it would be something like this but I'm not sure? Sorry for the newbie question.
let randomIndex: Int = Int(arc4random_uniform(UInt32(spDictionary.count)))`
Even for small data structures it's worth it to create a custom class or struct
struct Data {
let key : String
let value : String
let link : String
}
Create an object
let data = Data(key: "AMZN", value: "AMAZON", link: "yahoo")
Get a property
let link = data.link
and you can declare your dictionary
var spDictionary : [String: Data] = ...
So, I have an api call that'll output some raw json in the format below...
A bit messy, but I'm only interested in the Mapping portion of this json. If I had access to the raw data, I'd serialise the json cut to the dictionary / array I want to iterate through.. However the client is using restkit and this doesn't seem quite as easy as I'm imagining it....
Also What should I do with the Images section? Again, if was doing this with serialised json, I could open up the dictionary and set what's inside to an object with name description etc... can I do this as well?
{
"rsp": {
sn : "SerialNumber",
name : "Service Name",
from : "2000-01-01T00:00:00.000+01:00",
to : "2000-01-02T00:00:00.000+01:00",
mappings : {
"mapping" : {
"1" : {
from : 2000-06-01T00:01:00.000+01:00
to : 2000-06-01T01:02:00.000+01:00
content : {
name : "name"
description : "description"
images : {
image : "b47ab5a8.png"
}
}
},
"2" : {
from : 2000-06-01T00:01:00.000+01:00
to : 2000-06-01T01:02:00.000+01:00
content : {
name : "name"
description : "description"
images : {
image : "b47ab5a8.png"
}
}
},
// etc...
My question is
// what goes here
RKObjectMapping *itemMapping = [RKObjectMapping mappingForClass:[MYItem class]];
[itemMapping addAttributeMappingsFromDictionary:#{#"description":#"itemDescription",
#"name":#"name"}];
And how do I add the image to MYItem?
For the image your mapping is something like:
[itemMapping addAttributeMappingsFromDictionary:#{#"description":#"itemDescription",
#"name":#"name",
#"images.image":#"image"}];
i.e. key paths work
But, not that they only work for dictionaries. You can't index into arrays arbitrarily in the same way.
The key path is also in the response descriptor and that's how you drill down to the mapping, i.e. rsp.mappings.mapping (again, because it's dictionaries).
I have given JSON and cannot parse partial data. It seems dictionary into dictionary:
{
"products": [
{
"id": 6796,
"title": "my title",
"description": "desc",
"code": "12345",
"valueType": "null",
"discounts": [
{
"minPrice": null,
"maxPrice": null,
"value": 20,
"avail": false
}
]
}
]
}
I am using the latest version of RESTKit but I cannot properly parse under discounts.
my RestKit settings are:
responseMapping.addAttributeMappingsFromDictionary([
"id" : "id",
"code" : "code",
"title" : "title",
"valueType" : "valueType",
"description" : "desc",
"discounts.minPrice" : "minPrice",
"discounts.maxPrice" : "maxPrice",
"discounts.value" : "value",
"discounts.avail" : "avail",
])
but all values below discounts always return Nil. What I am doing wrong?
You can't directly map using discounts.XXX because discounts is an array and you have no way to index into that array and extract a single value.
You either need to change the source JSON to compress the values out of the dictionary, or create a custom object that you can map each item in the discounts array to.
Technically you could map the whole discounts array, which would give you an array of dictionaries, that you could then unpack in the setter method, but the array of custom objects is usually a better approach.
I'm trying to accomplish something really easily but I could not solve it to my beginner level in rails. The question is how do you assign a JSON objects attribute to a rails object.. I'm trying to send a request to Google Map's URL with some parameters. Without JSON parsing it works just fine, however when I try to parse it, I receive many errors. The regular JSON response from Google when I query the URL ([http://maps.googleapis.com/maps/api/directions/json?origin=40.983204,29.0216549&destination=40.99160908659266,29.02334690093994&sensor=false][1]) is like down below;
{
"routes" : [
{
"bounds" : {
"southwest" : {
"lat" : 40.98289,
"lng" : 29.02054
},
"northeast" : {
"lat" : 40.99148,
"lng" : 29.02388
}
},
"summary" : "Mühürdar Cd",
"waypoint_order" : [],
"legs" : [
{
"start_location" : {
"lat" : 40.98322,
"lng" : 29.02166
},
"distance" : {
"text" : "1.3 km",
"value" : 1324
},
And goes on.
The code I have to get the "summary" attribute is;
#request = Net::HTTP.get(URI.parse('http://maps.googleapis.com/maps/api/directions/json?origin=40.983204,29.0216549&destination=40.99160908659266,29.02334690093994&sensor=false'))
#result=JSON.parse(#request)["routes"]["summary"]
I wanted to ask what would be the proper way for me to get the summary attribute from the response?
hash['routes'][0]['legs'][0]['duration']['text']
would allow you to access Text and
hash['routes'][0]['legs'][0]['duration']['value']
the Value. Just try
hash['routes'][0]['legs'][0]['duration'].class
to see what type it is and access it accordingly