NSJSONSerialization - key names from array - iphone

I am parsing JSON data using objective-c.
The data is as follows:
{"parcels":{"12595884967":{"kj_number":"KJ6612636902","recipient":"Krzysztof Racki","courier":"3"}}}
I have an object "parcels" which has keys for packages. Now while I dont have a problem extracting this using JSONSerialization class, I am stuck figuring how to get a key name (i mean, how to read value 12595884967 from code).
Code:
if ( [ NSJSONSerialization isValidJSONObject:jsonObject ] ) {
// we are getting root element, the "parcels"
NSMutableSet* parcels = [ jsonObject mutableSetValueForKey:#"parcels" ];
// get array of NSDictionary*'ies
// in this example array has single NSDictionary* element with flds like "kj_number"
NSArray* array = [ parcels allObjects ];
for ( int i = 0 ; i < [ array count ] ; ++i ) {
NSObject* obj = [ array objectAtIndex: i ];
// the problem: how i get this dictionary KEY? string value of 12595884967
// how I should get it from code here?
// like: number = [ obj name ] or maybe [ obj keyName ]
if ( [ obj isKindOfClass:[ NSDictionary class ] ] ) {
// this always evaluates to true
// here we do reading attributes like kj_number, recipient etc
// and this works
}
}
}
for example in java it was:
JSONObject json = response.asJSONObject();
JSONObject parcels = json.getJSONObject( "parcels" );
#SuppressWarnings("unchecked")
Iterator<String> it = parcels.keys();
while ( it.hasNext() ) {
String key = it.next(); // value of 12595884967
Object value = parcel.getObject( key ); // JSONObject ref with data
}

A set doesn't store keys. You want to get a dictionary from the json.
NSDictionary* parcels = [jsonObject objectForKey:#"parcels"];
// get the keys
NSArray *keys = [parcels allKeys];
for (NSString *key in keys) {
NSDictionary *parcel = [parcels objectForKey:key];
// do something with parcel
}
Getting the keys in an array first is optional, you could iterate over the parcels dictionary directly: for (NSString *key in parcels) {.

I would propose to use a NSDictionary instead of NSMutableSet.
The NSDictionary has a method allKeys that will provide you with the requested data.

Related

How to access a certain value in an NSArray?

I have an array called someArray. I would like to access the name value of the NSArray. I'm trying to access it using the following, but with out any luck. How do I do it properly?
cell.textLabel.text = [[someArray objectAtIndex:indexPath.row] objectForKey:#"name"];
some array {
haserror = 0;
headers = {
code = 0;
haserror = 0;
nodeid = "fe1.aaaaaa.2.undefined";
time = 16;
};
results = (
{
coords = (
"44.916667",
"8.616667"
);
id = 2;
key = alessandria;
name = Alessandria;
state = Piemonte;
zip = 1512;
},
{
coords = (
"43.616944",
"13.516667"
);
id = 3;
key = ancona;
name = Ancona;
state = Marche;
zip = 601;
},
}
As far as i see from you data model, the key name is a node under the key results. You can use this data model as a dictionary map, the code snippet below must give you what you need..
NSDictionary *myObject = [[someArray objectAtIndex:indexPath.row] objectForKey:#"results"];
cell.textLabel.text = [myObject objectForKey:"name"];
IMPORTANT NOTE: If you have some lopps or some other mechanisms for receiving data, there may be more efficent ways for your sıolution, so please give some more additional info about what you are exactly tryin to do
As others have noted, someArray is a dictionary while results is a key pointing to an array inside of your dictionary. If you want an array of all of the name fields in your results array, you could use valueForKeyPath: on the someArray variable, like this:
NSArray *names = [someArray valueForKeyPath:#"results.name"];
The names variable should now contain "Alessandria", and "Ancona" from the data set your show in your example code.

Accessing info from NSDictionary based on print out

I'm using NSLog(#"%#", [filter attributes]); to print out the following from a dictionary:
CIAttributeFilterDisplayName = "Color Controls";
CIAttributeFilterName = CIColorControls;
inputBrightness = {
CIAttributeClass = NSNumber;
CIAttributeDefault = 0;
CIAttributeIdentity = 0;
CIAttributeSliderMax = 1;
CIAttributeSliderMin = "-1";
CIAttributeType = CIAttributeTypeScalar;
};
I'm a little confused about NSDictionarys and how the information is organized. If I needed to access the attributes for inputBrightness, what would be the syntax to retrieve this form the dictionary?
If you want to retrieve inputBrightness from dictionary filter, you can try this:
NSDictionary *inputBrightnessDict = filter[#"inputBrightness"]; //or [filter valueForKey:#"inputBrightness"];
This will return another dictionary with key value pairs CIAttributeClass:NSNumber, CIAttributeDefault:0 etc..
You can confirm that filter[#"inputBrightness"] is a dictionary by looking at the NSLog statement. Key value pairs enclosed in { and } represents a dictionary where as ( and ) represents an array.
Inorder to retrieve any value from inputBrightnessDict you can fetch it as, inputBrightnessDict[#"CIAttributeType"];
[filter objectForKey:inputBrightness];
Hope this helps..
Dictionary work with the concept of object and keys. You can retrieve an object using an key. Key-object come as a pair.

How to extract the following info from NSdictionary?

From the Dictionary,
key=key1 value1= {email = "test1#yahoo.com";
firstname = Joe;
lastname = Doe;
sessionid = "a21ed5ba-5039-11e0-9768-7136bb0a01e4";
"user_type" = 1; }
key=key2 value2={email = "test2#yahoo.com";
firstname = Dan;
lastname = Smith;
sessionid = "a20ed5ba-7039-21e0-6868-7136bb0a01e4";
"user_type" = 2; }
in other word, the value for key1 is bunch of info , not just a simple string.
Let the value be an array or object of user defined class.
#interface User : NSObject
{
NSString * email, * firstName, * lastName, * sessionId;
int userType;
}
you can create object of this class and insert it as a key-value pair in NSDictionary. And retrieve it back.
User * user = [dict objectForKey:key1];
Or you can insert a NSDictionary in a NSDictionary object and retrieve the values.
NSDictionary * dict1 = [dict objectForKey:key1];
NSString * email = [dict1 objectForKey:#"email"];
Hope this helps.
Here it seems that value1 is again a NSDictionary. So value1 is a dictionary key access the values using respective keys.
[dict objectForKey:key1]; will give you another NSDictionary.
So if you want to access e-mail from first dictionary with key as key1 you can try
[[dict objectForKey:key1] objectForKey:#"email"];

Decoding JSON with JSONKit gives error

I have the following JSON that validates as valid JSON..
{"flights":[{"flight":{"flightno":"BAW699","timestamp":"2011-03-22 07:06:02","route":"LOWW-EGLL"}},{"flight":{"flightno":"BAW706","timestamp":"2011-03-21 19:08:02","route":"EGLL-LOWW"}},{"flight":{"flightno":"BAW5MG","timestamp":"2011-03-21 16:33:02","route":"LEMG-EGLL"}},{"flight":{"flightno":"BAW3AG","timestamp":"2011-03-21 11:25:02","route":"EGLL-LEMG"}},{"flight":{"flightno":"BAW5EB","timestamp":"2011-03-20 19:18:02","route":"EGLL-LPPT"}},{"flight":{"flightno":"BA0489","timestamp":"2011-03-20 09:40:02","route":"LEBL-EGLL"}},{"flight":{"flightno":"BA0475","timestamp":"2011-03-19 16:51:02","route":"LEBL-EGLL"}},{"flight":{"flightno":"BAW489","timestamp":"2011-03-18 08:08:02","route":"LEBL-EGLL"}},{"flight":{"flightno":"BA0799","timestamp":"2011-03-17 18:37:02","route":"EGLL>EFHK"}},{"flight":{"flightno":"BAW799","timestamp":"2011-03-17 16:31:01","route":"EFHK-EGLL"}},{"flight":{"flightno":"BAW794","timestamp":"2011-03-17 11:55:02","route":"EGLL-EFHK"}},{"flight":{"flightno":"GEUUZ","timestamp":"2011-03-17 09:43:02","route":""}},{"flight":{"flightno":"BAW487","timestamp":"2011-03-16 19:32:01","route":"LEBL-EGLL"}},{"flight":{"flightno":"BAW486","timestamp":"2011-03-16 16:57:02","route":"EGLL-LEBL"}},{"flight":{"flightno":"BAW459","timestamp":"2011-03-16 14:10:01","route":"LEMD-EGLL"}},{"flight":{"flightno":"BAW41LM","timestamp":"2011-03-16 10:09:02","route":"EGLL-LEMD"}},{"flight":{"flightno":"BA0795","timestamp":"2011-03-16 08:27:02","route":""}},{"flight":{"flightno":"BAW795","timestamp":"2011-03-16 07:01:02","route":"EFHK-EGLL"}},{"flight":{"flightno":"BAW798","timestamp":"2011-03-15 18:23:02","route":"EGLL-EFHK"}},{"flight":{"flightno":"BAW701","timestamp":"2011-03-15 14:24:01","route":"LOWW-EGLL"}},{"flight":{"flightno":"BAW700","timestamp":"2011-03-15 11:04:01","route":"EGLL-LOWW"}},{"flight":{"flightno":"BAW68BL","timestamp":"2011-03-15 08:14:01","route":"LEBL-EGLL"}},{"flight":{"flightno":"BAW82BL","timestamp":"2011-03-14 18:40:03","route":"EGLL-LEBL"}},{"flight":{"flightno":"BAW849","timestamp":"2011-03-14 08:15:02","route":"EPWA-EGLL"}},{"flight":{"flightno":"BAW40CB","timestamp":"2011-03-13 19:30:03","route":"EGLL-LEBL"}},{"flight":{"flightno":"BAW475","timestamp":"2011-03-13 15:30:02","route":"LEBL-EGLL"}},{"flight":{"flightno":"z.NO-FLIGHTNO","timestamp":"2011-03-13 13:00:03","route":""}},{"flight":{"flightno":"BAW474","timestamp":"2011-03-13 12:00:03","route":"EGLL-LEBL"}},{"flight":{"flightno":"BAW4WP","timestamp":"2011-03-13 08:45:02","route":"LPPT-EGLL"}}]}
I then try and parse this using JSONKit but can only get as far down as "flights" I cannot seem to access the "flight" object.
When I do the following
-(void)parseJSON:(NSString *)jsonData{
NSDictionary *deserializedData = [jsonData objectFromJSONString];
for (id key in deserializedData) {
NSLog(#"key: %#, value: %#", key, [deserializedData objectForKey:key]);
}
}
Only the following is put out to the log....
key: flights, value: (
{
flight = {
flightno = BAW906N;
route = "EGLL-EDDF";
timestamp = "2011-03-24 08:38:02";
};
},
{
flight = {
flightno = BAW365;
route = "LFLL-EGLL";
timestamp = "2011-03-24 06:17:01";
};
},
{
flight = {
etc....
I want to be able to get down to each flight and at the moment am stuck!
Get an array of all flights like this:
NSArray *flights = [deserializedData valueForKeyPath:#"flights.flight"];
thats because you have an array of dictionairies in your dictionairy object, acces them like this:
for (NSDictionairy *flight in [deserializedData objectForKey:#"flights"]){
NSLog(#"flight object with route.: %#", [flight objectForKey:#"route"]);
}

Obj-C / iPhone: NSArray question

I have an array that looks like this when printed via NSLog:
{
response = "Valid";
updates = (
{
string = "test";
integer = 3493;
},
{
string = "test2";
integer = 55454;
}
);
start-index = 0;
My question is how I can loop through through the "updates" array so that I may print the values for each "string" respectively.
Should be an easy "for" loop or something?
Dave
Assuming you NSLogged data has a type of NSDictionary with name data.
NSArray *updates = [data objectForKey:#"updates"];
for (NSDictionary *update in updates) {
NSLog(#"Update: %# - %#", [update objectForKey:#"string"], [update objectForKey:#"integer"]);
}