I need to access the value of an NSArray by index. The following code crashes on line 3:
livevalues=[responseString JSONValue];
NSLog(#"%d",[livevalues count]);
NSString *objectvalue = [livevalues objectAtIndex:1];
NSLog(#"redyyyyyyyyyyy%#",objectvalue);
livevalues count is 4
livevalues array string is {"to": "INR", "rate": 53.801043700000001, "from": "USD", "v": 53.801043700000001}
I need values from that array is only 53.801043700000001 only
Use following expression
livevalues[1][#"rate"]
It is a Dictionary so Try like below
NSString *objectvalue = [livevalues objectForKey:#"rate"];
You have to use :
NSString *objectvalue = [[livevalues objectAtIndex:1] objectForKey:#"yourKey"];
to get the key for the desired string NSLog the description of the array and get your key from there
NSLog(#"%#",[livevalues description]);
Related
I am getting Names and ID's from DB... and storing those values in Array... Like Names storing in NamesArray and ID's storing in IDsArray...
Example:
NamesArray - {Peter, Arnold, John,Samuel}
IDsArray - {1, 2, 3,4}
After getting those values from DB... I am sorting NamesArray... It will come like this...
NamesArray Value - {Arnold,John,Peter,Samuel}
How to change the IDsArray according to the NamesArray?
The same scenario is needed for Search functionality....
Example:
I am searching 'P' text in SearchBar... It will show 'Peter' in TableView...
How to get the IDs from idarray according to the Searched Text?
Thanks in advance
You could use an array of dictionaries with keys Name and ID. After you could use NSPredicate for your search and NSSortDescriptor for sorting
yourArray: (
{
id = 1;
name = Peter;
},
{
id = 2;
name = Arnold;
},
{
id = 3;
name = John;
},
{
id = 4;
name = Samuel;
});
Sort
nameDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
nameDescriptors = [NSArray arrayWithObject:nameDescriptor];
sortedArray = [yourArray sortedArrayUsingDescriptors:nameDescriptors];
Filter
NSString *strToFilter = #"P";
NSArray *filteredNames = [yourArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(name BEGINSWITH[c] %#)", strToFilter]];
For this scenario simple logic can be done.
NamesArray - {Peter, Arnold, John,Samuel}
IDsArray - {1, 2, 3,4}
Have the searched names in separate array which will not affect NamesArray when you search.
searchedNamesArray - {Peter}
after that get the index of the searched object from array
for (NSString *value in searchedNamesArray)
{
NSInteger index = [NamesArray indexOfObject:value];
// you will get the index of the object from which you can use from getting the id from IDsArray
NSLog(#"ID - %#", [IDsArray objectAtIndex:index]);
}
I'm getting JSON data like following in a NS array:
It seems this is not valid JSON
jsonArray:
{
d = "[{\"Training_Code\":\"1234 \",\"Training_Duration\":\"2hrs \",\"Training_Startdate\":\"14/02/2013 15:00:00\",\"Training_Enddate\":\"14/02/2013 17:00:00\",\"Trainer_ID\":1,\"Training_Location\":\"B-Wing Training room-4\",\"Comments\":\"C# training\",\"Keyword\":\"C#1234\",\"NumberofDays\":1},{\"Training_Code\":\"4321 \",\"Training_Duration\":\"16 \",\"Training_Startdate\":\"17/02/2013 10:30:00\",\"Training_Enddate\":\"17/02/2013 17:30:00\",\"Trainer_ID\":2,\"Training_Location\":\"A-Wing Training Room-6\",\"Comments\":\"Objective-C\",\"Keyword\":\"Obj-C4321\",\"NumberofDays\":2}]";
}
I want to change this to valid json like this:
[
{
"Training_Code": "1234",
"Training_Duration": "2hrs",
"Training_Startdate": "14/02/201315: 00: 00",
"Training_Enddate": "14/02/201317: 00: 00",
"Trainer_ID": 1,
"Training_Location": "B-WingTrainingroom-4",
"Comments": "C#training",
"Keyword": "C#1234",
"NumberofDays": 1
},
{
"Training_Code": "4321",
"Training_Duration": "16",
"Training_Startdate": "17/02/201310: 30: 00",
"Training_Enddate": "17/02/201317: 30: 00",
"Trainer_ID": 2,
"Training_Location": "A-WingTrainingRoom-6",
"Comments": "Objective-C",
"Keyword": "Obj-C4321",
"NumberofDays": 2
}
]
Note: I do not know, from where this "d" is comming...Plaese suggest keeping this in mind.
How can I change to valid json and insert this in my Sqlite DB? Thanks.
You can always inset it as plain text. If you want to manipulate JSON Strings, I recommend this. You can transform that String into a JKArray (which is the same than an Array). After that, iterate through your array and do your DB stuff (inserting into your table...)
Am I missing something? Maybe I need more info about what you want to do...
That's a string containing an encoded JSON array. You need to use a JSON decoder (batteries included as of iOS 5) to convert it into an NSArray, then walk it:
The following (untested) code should be about right:
// Assuming jsonArray is an object with an NSString property, d...
NSData *data = [jsonArray.d dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSArray *d = [NSJSONSerialization JSONObjectWithData:data options:0 error:err];
// Check for errors.
for (NSDictionary *row in d) {
NSString *trainingCode = [row objectForKey:#"Training_Code"];
…
// Insert into SQLite here.
}
Note that, in recent versions of Xcode, you can write row[#"Training_Code"] instead of [row objectForKey:#"Training_Code"].
Parse your json using NSJSONSerialization and insert into database by mapping keys with your columns.
NSString *str = [[NSString alloc] initWithString:#"[{\"Training_Code\":\"1234 \",\"Training_Duration\":\"2hrs \",\"Training_Startdate\":\"14/02/2013 15:00:00\",\"Training_Enddate\":\"14/02/2013 17:00:00\",\"Trainer_ID\":1,\"Training_Location\":\"B-Wing Training room-4\",\"Comments\":\"C# training\",\"Keyword\":\"C#1234\",\"NumberofDays\":1},{\"Training_Code\":\"4321 \",\"Training_Duration\":\"16 \",\"Training_Startdate\":\"17/02/2013 10:30:00\",\"Training_Enddate\":\"17/02/2013 17:30:00\",\"Trainer_ID\":2,\"Training_Location\":\"A-Wing Training Room-6\",\"Comments\":\"Objective-C\",\"Keyword\":\"Obj-C4321\",\"NumberofDays\":2}]"];
NSError *jsonError = nil;
id allValues = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:&jsonError];
if(jsonError!=nil)
InfoLog(#"error: %#",jsonError);
NSArray *result = (NSArray*)allValues;
for(int i=0;i<[result count];i++)
{
NSDictionary *values = (NSDictionary*)[result objectAtIndex:i];
NSLog(#"Training_Code: %# Training_Duration: %#",[values objectForKey:#"Training_Code"],[values objectForKey:#"Training_Duration"]);
}
Now you are able to get values from NSDictionary and then simply add in your database.
What I'm trying to do is take a JSON feed and then loop through the results. However I keep getting a string instead of an array when I get the object from the dictionary. Any ideas on what I'm doing wrong?
Here's the JSON:
[
{
"_id": "4f6d9a7c1d0b4900010007ee",
"geo_triggers": [
{
"_id": "4fc3e5fdc7234e0001000002",
"location": [1,1],
"longitude": "1",
"latitude": "1",
"radius": 1,
"location_name": "Test 1"
},
{
"_id": "4fc61f3762f53f0001000043",
"location": [-71.057673,42.355395],
"longitude": "-71.057673",
"latitude": "42.355395",
"radius": 1000,
"location_name": "Test2"
}
]
}
]
Here's the Objective C Code:
const char* className = class_getName([result class]);
NSLog(#"Result is a: %s", className);
NSLog(#"%#", result); //string
NSArray* json = [result objectForKey:#"result"]; //should be an array of dictionaries
NSLog(#"JSON Output: %#", json);
const char* className1 = class_getName([json class]);
NSLog(#"yourObject is a: %s", className1);
And here's the output:
Result is a: __NSDictionaryI
2012-10-10 17:15:15.165 App[12980:19d03] {
result = "[{\"_id\":\"4f6d9a7c1d0b4900010007ee\",\"geo_triggers\":[{\"_id\":\"4fc3e5fdc7234e0001000002\",\"location\":[1.0,1.0],\"longitude\":\"1\",\"latitude\":\"1\",\"radius\":1,\"location_name\":\"Test 1\"},{\"_id\":\"4fc61f3762f53f0001000043\",\"location\":[-71.057673,42.355395],\"longitude\":\"-71.057673\",\"latitude\":\"42.355395\",\"radius\":1000,\"location_name\":\"Test2\"}]}]";
}
2012-10-10 17:15:15.166 App[12980:19d03] JSON Output: [{"_id":"4f6d9a7c1d0b4900010007ee","geo_triggers":[{"_id":"4fc3e5fdc7234e0001000002","location":[1.0,1.0],"longitude":"1","latitude":"1","radius":1,"location_name":"Test 1"},{"_id":"4fc61f3762f53f0001000043","location":[-71.057673,42.355395],"longitude":"-71.057673","latitude":"42.355395","radius":1000,"location_name":"Test2"}]}]
2012-10-10 17:15:15.166 App[12980:19d03] yourObject is a: __NSCFString
2012-10-10 17:15:15.166 App[12980:19d03] -[__NSCFString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0xb331800
Your result variable points to a dictionary. The dictionary contains one key. That key is #"result". The value for that key is a string, #"[{\"_id\":\"4f6d9a7c1d0b4900010....
In other words, you haven't really deserialized your JSON. You need to take the value for key result and run it through a JSON deserializer.
First need to decode the result. The above is JSON so I would suggest doing this
If you don't already have it download JSONKit.h and include it in your project
Then you can either do
NSString* json = [result JSONString]; to see the output
OR
something like id jsonDict = [[JSONDecoder decoder] objectWithData:responseData];
After that you can do [jsonDict objectForKey:#"_id"]; ///etc
I have a NSMutableArray containing NSURLConnection descriptions, like so:
array {
"<NSURLConnection: 0x60eb40>",
"<NSURLConnection: 0x6030e0>",
"<NSURLConnection: 0x602ce0>",
"<NSURLConnection: 0x60c330>",
"<NSURLConnection: 0x662f5a0>",
}
I have also a NSMutableDictionary whose keys are the items from the above NSMutableArray, like so:
dictionary {
"<NSURLConnection: 0x602ce0>" = "Last update: Sep 3, 2012";
"<NSURLConnection: 0x6030e0>" = "Last update: Sep 7, 2012";
"<NSURLConnection: 0x60c330>" = "Last update: Sep 4, 2012";
"<NSURLConnection: 0x60eb40>" = "Last update: Sep 6, 2012";
"<NSURLConnection: 0x662f5a0>" = "Last update: Sep 5, 2012";
}
I need to reorder the NSMutableDictionary to match the same order of the NSMutableArray indexes. Right now I'm doing like this:
int a;
for (a=0; a<self.array.count; a++) {
NSString *key = [self.array objectAtIndex:a];
NSString *object = [self.dictionary objectForKey:key];
if (object !=nil) {
[self.array removeObjectAtIndex:a];
[self.array insertObject:object atIndex:a];
}
}
Is there a better way to reorder this NSMutableDicitioanry to match the order of the NSMutableArray ?
Thank you!
NSDictionary does not guarantee any ordering of it's key/value pairs. There's no way to keep your keys/values in a set order and it doesn't make sense for NSDictionary to work like this. (You use keys not indexes to retrieve values).
If you want your values or keys in a certain order for display purposes you can sort them after retrieving them:
NSArray * sortedKeys = [ [ myDictionary allKeys ] sortedArrayUsingSelector:... ] ;
or
NSArray * sortedKeys = [ [ myDictionary allKeys ] sortedArrayUsingComparator:... ] ;
You could then retrieve the associated objects for the sorted keys if you wanted.
Another option is to maintain 2 separate arrays, one for keys and one for values and keep them in order.
(
{
dateVal = "nov 26, 2010";
price = "1 - 195 kr";
},
{
dateVal = "nov 26, 2010";
price = "425 - 485 kr";
},
{
dateVal = "nov 26, 2010";
price = "415 - 640 kr";
})
How can i extract this NSMutableDictionay?
Help me!
You have plenty of choices (I suggest looking into NSArray class reference)
To get dictionary at specific index (whether dictionary you get is mutable or not depends, I think, on how have you created them and put them in array)
// make sure that index is in array bounds
NSDictionary* dict = [yourArray objectAtIndex:index];
NSLog(#"%#", [dict objectForKey:#"dateVal"]); // log date
NSLog(#"%#", [dict objectForKey:#"price"]); // log price
If you want to iterate through all dictionaries you have then you can use fast enumeration:
for (NSDictionary* dict in yourArray){
...
}
It seems to be an Array which contains Dictionnary.
But Vladimir is right, how did you get this ?
To get an item from a Dictionnary, use this :
[ dictionnary objectForKey:#"keyName" ];
Do you mean converting from this string to NSDictionary? It looks like a JSON String for me, doesn't it?
If it is a JSON String and you want to convert to a NSDictionary, you may want to use TouchJSON, some tutorial here