in response, i am getting gas_cylinders key as single array object
"gas_cylinders":["[{\"quantity\":\"2\",\"name\":\"Medium Blue\",\"price\":\"100.0\",\"total_price\":\"200.0\"},{\"quantity\":\"3\",\"name\":\"Green\",\"price\":\"100.0\",\"total_price\":\"300.0\"},{\"quantity\":\"1\",\"name\":\"Dark Green\",\"price\":\"100.0\",\"total_price\":\"100.0\"}]"]
Note:- tripDictionary contain below data..
(lldb) po tripDictionary
{
"gas_cylinder_total" = 600;
"gas_cylinders" = (
"[{\"quantity\":\"2\",\"name\":\"Medium Blue\",\"price\":\"100.0\",\"total_price\":\"200.0\"},{\"quantity\":\"3\",\"name\":\"Green\",\"price\":\"100.0\",\"total_price\":\"300.0\"},{\"quantity\":\"1\",\"name\":\"Dark Green\",\"price\":\"100.0\",\"total_price\":\"100.0\"}]"
);
}
i am taking gas_cylinders like below way..
NSArray *arr = [tripDictionary valueForKey:#"gas_cylinders"];
if (arr && arr.count > 0) {
NSLog(#"first obj = %#",arr[0]);
}
output of above NSLog like..
first obj = [{"quantity":"2","name":"Medium Blue","price":"100.0","total_price":"200.0"},{"quantity":"3","name":"Green","price":"100.0","total_price":"300.0"},{"quantity":"1","name":"Dark Green","price":"100.0","total_price":"100.0"}]
how can i get this object in NSMutableArray ?
The data is not what you think it is. The value of the gas_cylinders key is an array of JSON string.
NSArray *cylinders = tripDictionary[#"gas_cylinders"];
NSString *firstCylinder = cylinders[0];
At this point, firstCylinder is a JSON string. You need to parse that JSON string to get the desired array of dictionaries contained in the JSON string.
Related
Below is my Response
geolocation = {
loc = {
lat = "22.4409980000000004451976565178";
long = "70.0686230000000023210304789245";
};
};
My app crashes when I try below code:
NSNumber* n = [userPin valueForKeyPath:#"geolocation.loc.lat"];
NSLog(#"num is class %#", NSStringFromClass([n class]));
float fCost = [n floatValue];
When I print my NSStringFromClass I get __NSSingleObjectArrayI.
Any suggestion how to fix this?
At a guess the (runtime) type of userPin is array and it contains one element. When applied to an array valueForKey:, on which valueForKeyPath: is based, returns an array produced by applying itself to every element of the array.
If this is the case either index userPin before the call or handle the array resulting from the call.
Addendum
Could you give me an example?
Trivial example:
// An array of strings
NSArray *test = #[ #"The", #"quick", #"brown", #"fox"];
// Trivial keypath...
NSArray *result = [test valueForKeyPath:#"length"];
// Print
NSLog(#"%#", result);
Produces:
(
3,
5,
5,
3
)
showing result is an array of the result of applying length to each element of `test. HTH
I have an array with arrays. I do:
predicateWithFormat:#"ANY SELF == %#",temphref];
NSArray *results = [shareArray filteredArrayUsingPredicate:predicate];
And if I print
(
(
"id=77",
"path=/cp012725.exe",
"share_type=3",
"token=88ae683504def4caab9154f1684dccdf"
) )
I would like to get these Array values into strings. stringForID stringForPath stringForShareType
stringForToken
I try to just NSString *stringForID = results[0][0];
But it fails when the array is empty, but array does not respond to if(results==nil)
if I print the resultswhen there are none, it prints ()so its not nil i guess.
Any suggestions?
The filter will always return an array, even if its empty, change your if statement from...
if(results==nil)
to this
if(results.count == 0)
I have NSArray of NSDictionaries I need to extract 2 values or remove the values I don't need from the dictionary in the example below I need to remove id and NumberValue. any of you knows how can I do that?
Array: (
{
customerUS= {
DisplayName = "level";
InternalName = "Number 2";
NumberValue = 1;
id = xwrf
},
customerCAN= {
DisplayName = "PurchaseAmount";
InternalName = "Number 1";
NumberValue = 3500;
id = adf;
};
}
)
I'll really appreciate your help.
First thing, You can not remove/insert/update value in (immutable) NSDictionary/NSArray you need to convert NSDictionary/NSArray to (mutable) NSMutableDictionary/NSMutableArray.
such like
NSArray *myArr = ....;
NSMutableArray *newMutableArr = [myArr mutableCopy];
Then you can change in newMutableArr.
Such like
for(int i = 0 ; i < newMutableArr.count ; i ++)
{
[[newMutableArr objectAtIndex:i] removeObjectForKey:#"id"];
[[newMutableArr objectAtIndex:i] removeObjectForKey:#"NumberValue"];
}
EDITED:
Without Use of for loop and removeObjectForKey, if you have array of dictionary and both are mutable then you can also delete a key and its object from all elements of the array like this:
[newMutableArr makeObjectsPerformSelector:#selector(removeObjectForKey:) withObject:#"id"];
[newMutableArr makeObjectsPerformSelector:#selector(removeObjectForKey:) withObject:#"NumberValue"];
I would advice you to read Apple documents.
For modifying any Collection object after it is created, you need the mutable version.
For NSDictionary we have NSMutableDictionary. Read here.
We have a method for removing objects:
- (void)removeObjectForKey:(id)aKey
There are other methods as well. You can easily refer them in the above mentioned documentation.
Find out removeObjectForKey for deleting record from NSMutabledictionary.
removeObjectForKey pass the key value whatever you have like
all this are your key
DisplayName,
InternalName,
NumberValue,
id
do like this
removeObjectForKey:#"id";
First of all you have to convert the array to mutable array and then you can remove the key-value pairs from dictionary.
NSMutableArray *mutableArray = [yourArray mutableCopy];for(int i=0;i<mutableArray.count;i++){ NSMutableDictionary *outerDictionary = [mutableArray objectAtIndex:i]; for(NSString *key in outerDictionary.allKeys){ NSMutableDictionary *innerDictionary = [outerDictionary objectForKey:key]; [innerDictionary removeObjectForKey:#"id"]; [innerDictionary removeObjectForKey:#"NumberValue"]; }
}
I used json-framework to pull a JSON string from and URL and convert the JSON string to NSDictionary object with these two lines of code
SBJsonParser* parser = [SBJsonParser new];
NSDictionary* myDict = [parser objectWithString:resp];
My NSDicitonary has:
(
{
condition = no;
date = "2013-06-21";
"location_id" = 9;
name = Chabahil;
reason = "";
time = "03:04:22";
},
{
condition = pressure;
date = "2013-06-21";
"location_id" = 7;
name = Maitighar;
reason = "Peak Hour";
time = "03:04:13";
}
)
Now I need to access each element for example I want to get value of "name" of the second element. I couldnot figure out how to do it.
Thanks!
The JSON string contains not a dictionary, but an array (of two dictionaries).
So you would do
SBJsonParser* parser = [SBJsonParser new];
NSArray* jsonArray = [parser objectWithString:resp];
and access the values for example like
NSString *secondName = [[jsonArray objectAtIndex:1] objectForKey:#"name"];
or, using the modern subscripting syntax:
NSString *secondName = jsonArray[1][#"name"];
(Note that there already is a NSJSONSerialization class in Foundation, so unless you
have a specific reason to use SBJsonParser, you could use that as well.)
I am currently trying to work with json and objective-c however having a bit of difficulty. The following is the json that is being returned
{
sethostname = (
{
msgs = "Updating Apache configuration\nUpdating cPanel license...Done. Update succeeded.\nBuilding global cache for cpanel...Done";
status = 1;
statusmsg = "Hostname Changed to: a.host.name.com";
warns = (
);
});
}
I am able to check that the response is coming back and the key is sethostname however no matter what I try I cannot get for example the value of status or statusmsg. Can anyone point me in the right location. The following is basic code I am using to check that sethostname is returned.
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&myError];
NSLog([res description]);
NSArray *arr;
arr = [res allKeys];
if ([arr containsObject:#"sethostname"])
{
NSLog(#"worked");
}
When in doubt, write down the structure of your JSON data. For example:
{
sethostname = (
{
msgs = "Updating Apache configuration\nUpdating cPanel license...Done. Update succeeded.\nBuilding global cache for cpanel...Done";
status = 1;
statusmsg = "Hostname Changed to: a.host.name.com";
warns = (
);
});
}
(which is in NeXTSTEP property list format, actually) means that you have a top-level dictionary. This top-level dictionary contains a key called sethostname whose value is an array. This array is comprised of dictionaries, each dictionary having a set of keys: msgs, status, statusmsg, warns. msgs has a string value, status has a number value, statusmsg has a string value,warns` has an array value:
dictionary (top-level)
sethostname (array of dictionaries)
dictionary (array element)
msgs (string)
status (number)
statusmsg (string)
warns (array)
??? (array element)
Having understood this structure, your code should look like:
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&myError];
if (!res) { // JSON parser failed }
// dictionary (top-level)
if (![res isKindOfClass:[NSDictionary class]]) {
// JSON parser hasn't returned a dictionary
}
// sethostname (array of dictionaries)
NSArray *setHostNames = [res objectForKey:#"sethostname"];
// dictionary (array element)
for (NSDictionary *setHostName in setHostNames) {
// status (number)
NSNumber *status = [setHostName objectForKey:#"status"];
// statusmsg (string)
NSString *statusmsg = [setHostName objectForKey:#"statusmsg"];
…
}
Why not use the simplest JSON method - [myString jsonValue];
It's part of this JSON framework for objective-c
I don't think if ([arr containsObject:#"sethostname"]) is going to work, because the results array is not going to contain that exact object. It might contain an object with the same content, but it won't be the SAME object.
As jtbandes wrote, you need to log the actually output. NSLog both res and arr and see what you have.