How can I loop through this part of the json [{first set of values},{data->children->data->body} in objective c?
Json is
[
{
"kind": "Listing"
},
{
"kind": "Listing",
"data": {
"children": [
{
"data": {
"body": "body1"
}
},
{
"data": {
"body": "body2"
}
}
]
}
}
]
My current code is
m_ArrList=[[NSMutableArray alloc]init];
NSDictionary *infomation = [self dictionaryWithContentsOfJSONString:#"surveyquestion.json"];
NSArray *array=[infomation objectForKey:#"data"];
int ndx;
NSLog(#"%#",array);
for (ndx = 0; ndx < [array count]; ndx++) {
NSDictionary *stream = (NSDictionary *)[array objectAtIndex:ndx];
NSArray *string=[stream valueForKey:#"children"];
//i am stuck here
}
What do I do at the "//i am stuck here" ?
You might need to add the values of #"children" dictionary in an array and then parse that array to get the data inside children
[childrenArray addObject:[stream objectForKey:#"children"]];
// finally parse childrenArray
// You Just need to Implement following Lines and you will get all the data for Key Body in children array
NSDictionary *infomation = [self dictionaryWithContentsOfJSONString:#"surveyquestion.json"];
NSArray *string= [[infomation objectForKey:#"data"] objectForKey:#"children"];
[string enumerateObjectsUsingBlock:^(id obj, NSUInteger ind, BOOL *stop){
NSLog(#"Body : %#",[[obj objectForKey:#"data"] objectForKey:#"body"]);
}];
Using NSJSONSerialization try to implement this. Here you need to pass NSString as jsonStr which you need to read from your file.
NSError *jsonError = nil;
id allValues = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:&jsonError];
if(jsonError!=nil)
NSLog(#"Json_Err: %#",jsonError);
NSArray *array=allValues;
for (int ndx = 0; ndx < [array count]; ndx++) {
NSDictionary *stream = (NSDictionary *)[array objectAtIndex:ndx];
NSLog(#"%#",[stream objectForKey:#"kind"]);
NSArray *child = [[stream objectForKey:#"data"] objectForKey:#"children"];
//i am stuck here
for(int i =0; i <[child count];i++)
{
NSDictionary *childData = (NSDictionary *)[child objectAtIndex:i];
//NSLog(#"%#",[childData objectForKey:#"data"]);
NSLog(#"%#",[[childData objectForKey:#"data"] objectForKey:#"body"]);
}
}
Related
{
distance = "0.03159804520191554";
rid = 374824705969;
uuid = "1838346268_374823983610_2016-08-08T07:32:08.679GMT";
},
{
rid = 374824705969;
uuid = "1838346268_374823983610_2016-08-08T07:32:08.679GMT";
},
{
rid = 374824706065;
uuid = "1838346268_374823983610_2016-08-08T07:32:22.680GMT";
}
This is what I got from the array of dictionaries. I want to remove duplicates where rid=374824705969 without using loops.Can any one help me.
Thanks in advance.
Try these one:
NSArray *array = #[
#{
#"rid" : #374824705969,
#"uuid" : #"1838346268_374823983610_2016-08-08T07:32:08.679GMT"
},
#{
#"rid" : #374824705969,
#"uuid" : #"1838346268_374823983610_2016-08-08T07:32:08.679GMT"
},
#{
#"rid" : #374824706065,
#"uuid" : #"1838346268_374823983610_2016-08-08T07:32:22.680GMT"
}];
NSMutableSet *keys = [NSMutableSet new];
NSMutableArray *result = [NSMutableArray new];
for (NSDictionary *data in array) {
NSString *key = data[#"rid"];
if ([keys containsObject:key]) {
continue;
}
[keys addObject:key];
[result addObject:data];
}
NSLog(#"%#", result);
I have managed to extract the following array (which I am dumping to console) from some json. How can I get and print out the value for one of the elements, i.e. task?
Objective-C:
NSArray *array = [dict objectForKey:#"row"];
NSLog(#"array is: %#",array);
Console output:
array is: {
0 = 1;
1 = "send email";
2 = "with attachment";
ltask = "with attachment";
task = "send email";
userid = 1;
}
array looks like it is actually an NSDictionary, so reference the key to get the value for it.
NSLog(#"Task: %#", array[#"task"]);
the variable array doesn't seem to be NSArray . Does this work for you?
id array = [dict objectForKey:#"row"];
if([array isKindOfClass:[NSDictionary class]]){
NSLog(#"Value of task %#",array[#"task"]);
}
From the log, it looks like the output is an NSDictionary object, so to get the value of task key just do this
NSDictionary *myDict = dict[#"row"];
NSString *task = myDict[#"task"];
NSLog(#"task = %#", task);
if you want to confirm just check the class type using isKindOfClass: method
if([dict[#"row"] isKindOfClass:[NSDictionary class]]) {
NSDictionary *myDict = dict[#"row"];
NSString *task = myDict[#"task"];
NSLog(#"task = %#", task);
} else if([dict[#"row"] isKindOfClass:[NSArray class]]) {
NSArray *myArray = dict[#"row"];
NSDictionary *myDict = myArray[0];
NSString *task = myDict[#"task"];
NSLog(#"task = %#", task);
}
try
if ([[dictionary allKeys] containsObject:#"row"]) {
NSObject *objRow = dictionary[#"row"];
if(objRow){
if([objRow isKindOfClass:[NSArray class]]){
NSArray *arr = (NSArray *)objRow;
....
}
if([objRow isKindOfClass:[NSDictionary class]]){
NSDictionary *dic = (NSDictionary *)objRow;
....
}
}
}
I have a problem to communicate with a server. The webserver expects all parameters in the JSON object to be a string. So every number and every boolean in every container needs to be a string.
For my example I have a NSDictionary full of key values (values are all kinds of types - numbers, arrays etc.). For example:
{
"AnExampleNumber":7e062fa,
"AnExampleBoolean":0,
"AnExampleArrayOfNumber":[17,4,8]
}
Has to become:
{
"AnExampleNumber":"7e062fa",
"AnExampleBoolean":"0",
"AnExampleArrayOfNumber":["17","4","8"]
}
I tried the standard NSJSONSerializer but it doesn't give me any option to do what I need. I then tried to transform everything in the dictionary manually to be a string but that seems to be overhead. Does anyone have hint for me? Maybe a serializer that does just that or a function to convert any objects in a container to strings?
This is one way you could do it. It's non-optimized and has no error handling. It only supports the kinds of objects that NSJSONSerializer supports.
#import <Foundation/Foundation.h>
#interface NSObject(SPWKStringify)
- (id)spwk_stringify;
#end
#implementation NSObject(SPWKStringify)
- (id)spwk_stringify
{
if ([self isKindOfClass:[NSDictionary class]]) {
NSDictionary *dict = (NSDictionary *)self;
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
for (NSString *key in [dict allKeys]) {
newDict[key] = [dict[key] spwk_stringify];
}
return newDict;
} else if ([self isKindOfClass:[NSArray class]]) {
NSMutableArray *newArray = [[NSMutableArray alloc] init];
for (id value in ((NSArray *)self)) {
[newArray addObject:[value spwk_stringify]];
}
return newArray;
} else if (self == [NSNull null]) {
return #"null"; // representing null as a string doesn't make much sense
} else if ([self isKindOfClass:[NSString class]]) {
return self;
} else if ([self isKindOfClass:[NSNumber class]]) {
return [((NSNumber *)self) stringValue];
}
return nil;
}
#end
int main(int argc, char *argv[]) {
#autoreleasepool {
NSDictionary *dict = #{
#"AnExampleNumber": #1234567,
#"AnExampleBoolean": #NO,
#"AnExampleNull": [NSNull null],
#"AnExampleArrayOfNumber": #[#17, #4, #8],
#"AnExampleDictionary": #{#"innerKey": #[#55, #{#"anotherDict": #[#"foo", #[#1, #2, #"three"]]}]}
};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[dict spwk_stringify] options:NSJSONWritingPrettyPrinted error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"result: %#", jsonString);
}
}
The output will be:
result: {
"AnExampleNumber" : "1234567",
"AnExampleNull" : "null",
"AnExampleDictionary" : {
"innerKey" : [
"55",
{
"anotherDict" : [
"foo",
[
"1",
"2",
"three"
]
]
}
]
},
"AnExampleBoolean" : "0",
"AnExampleArrayOfNumber" : [
"17",
"4",
"8"
]
}
Note: Please keep in mind that turning [NSNull null] into a string doesn't make any sense and might actually be misleading and dangerous.
Enjoy.
(I assume you mean NSJSONSerializer, not NSSerializer.)
I doubt you'll find a pre-rolled solution to this. It's not a general problem. As you note, this is incorrect JSON, so JSON serializers shouldn't do it.
The best solution IMO is just write the code to transform your NSDictionary into another NSDictionary that is in the form you want. If you really want to make it a generic solution, I suspect that a custom NSDictionary walker with isKindOfClass: is your best bet. Something like this should work:
NSDictionary *myStringDictForDict(NSDictionary *dict); // forward decl if needed
NSArray *myStringArrayForArray(NSArray *array) {
NSMutableArray *result = [NSMutableArray new];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isKindOfClass:[NSArray class]]) {
[result addObject:myStringArrayForArray(obj)];
} else if ([obj isKindOfClass:[NSDictionary class]]) {
[result addObject:myStringDictForDict(obj)];
} else {
[result addObject:[obj description]];
}
}];
return result;
}
NSDictionary *myStringDictForDict(NSDictionary *dict) {
NSMutableDictionary *result = [NSMutableDictionary new];
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([obj isKindOfClass:[NSArray class]]) {
result[key] = myStringArrayForArray(obj);
} else if ([obj isKindOfClass:[NSDictionary class]]) {
result[key] = myStringDictForDict(obj);
} else {
result[key] = [obj description];
}
}];
return result;
}
It seems that since XCode 6.1, the iPhone 5S, iPhone 6 and iPhone 6+ simulators (all 64-bit) all return data from the following system method differently (keys are ordered differently) than their 32-bit simulator counterparts (e.g. iPhone 5 simulator)
+ (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;
This difference of key ordering caused a problem for me since we calculate the SHA1 of that JSON data (converted to NSString*) and use it for a validation test. Since the ordering changed, the SHA1 changed and the validation fails.
Simplified sample code (non-ARC) to get the SHA1 is below:
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:0
error:&error];
NSString * json = [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] autorelease];
NSString * sha1 = [MyUtils computeSHA1:json];
+(NSString*) computeSHA1:(NSString*)input
{
const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:input.length];
NSNumber* dataLen = [NSNumber numberWithUnsignedInteger:data.length];
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes, dataLen.unsignedIntValue, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
[output appendFormat:#"%02x", digest[i]];
return output;
}
Apparently, this key ordering difference doesn't happen on the actual devices (previous behavior was preserved).
I also tried with the NSJSONWritingPrettyPrinted option but the JSON ordering is still inconsistent between simulators.
So, the question is: Does anyone have a recommendation on how to normalize such JSON data so as to not be susceptible to key ordering changes? Alternately, is there any way to get the previous (32-bit simulator) behavior?
Key ordering in dictionaries is not guaranteed. If you need them sorted, put them into an array and sort them.
The code below (non-ARC) worked for me to better canonicalize JSON output. The code assumes the class methods below are all in a class called MyUtils.
Simply pass the the NSDictionary to serialize into "canonicalized JSON" to canonicalJSONRepresentationWithDictionary:
The returned NSString* then contains serialized JSON that has the keys ordered lexicographically/alphabetically in a non-human readable format.
+(NSString *) canonicalJSONRepresentationWithDictionary:(NSDictionary *)dict
{
NSMutableString* json = [NSMutableString string];
[json appendString:#"{"];
NSArray* keys = [[dict allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString* a, NSString* b) {
return [a compare:b];
}];
for (int i = 0; i < keys.count; i++) {
NSString* key = keys[i];
[json appendFormat:#"\"%#\":", key];
if ([dict[key] isKindOfClass:[NSString class]]) {
[json appendFormat:#"\"%#\"", [MyUtils canonicalJSONRepresentationWithString:dict[key]]];
} else if ([dict[key] isKindOfClass:[NSDictionary class]]) {
[json appendString:[MyUtils canonicalJSONRepresentationWithDictionary:dict[key]]];
} else if ([dict[key] isKindOfClass:[NSArray class]]) {
[json appendString:[MyUtils canonicalJSONRepresentationWithArray:dict[key]]];
} else {
return nil;
}
if (i < keys.count - 1) {
[json appendString:#","];
}
}
[json appendString:#"}"];
return json;
}
+(NSString *) canonicalJSONRepresentationWithArray:(NSArray *) array
{
NSMutableString* json = [NSMutableString string];
[json appendString:#"["];
for (int i = 0; i < array.count; i++) {
if ([array[i] isKindOfClass:[NSString class]]) {
[json appendFormat:#"\"%#\"", [MyUtils canonicalJSONRepresentationWithString:array[i]]];
} else if ([array[i] isKindOfClass:[NSDictionary class]]) {
[json appendString:[MyUtils canonicalJSONRepresentationWithDictionary:array[i]]];
} else if ([array[i] isKindOfClass:[NSArray class]]) {
[json appendString:[MyUtils canonicalJSONRepresentationWithArray:array[i]]];
} else {
return nil;
}
if (i < array.count - 1) {
[json appendString:#","];
}
}
[json appendString:#"]"];
return json;
}
+(NSString *) canonicalJSONRepresentationWithString:(NSString *) string;
{
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:string, #"a", nil];
NSError * error;
NSData * jsonData = nil;
NSString * json = nil;
jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:0
error:&error];
if (!jsonData) {
NSLog(#"Got an error serializing json: %#", error);
return nil;
} else {
json = [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] autorelease];
}
NSRange colonQuote = [json rangeOfString:#":\""];
NSRange lastQuote = [json rangeOfString:#"\"" options:NSBackwardsSearch];
NSRange range = NSMakeRange(colonQuote.location + 2, lastQuote.location - colonQuote.location - 2);
NSString* rc = [json substringWithRange:range];
return rc;
}
I'm trying to parse this JSON:
{
"GetMachineGroupsResult": {
"MachineGroups": [
{
"GroupCount": 1,
"GroupID": 101,
"GroupName": "Machine11"
},
{
"GroupCount": 6,
"GroupID": 201,
"GroupName": "Machine12"
},
{
"GroupCount": 1,
"GroupID": 301,
"GroupName": "Machine13"
},
{
"GroupCount": 1,
"GroupID": 501,
"GroupName": "Machine14"
},
{
"GroupCount": 7,
"GroupID": 701,
"GroupName": "Machine15"
},
{
"GroupCount": 1,
"GroupID": 901,
"GroupName": "Machine16"
},
{
"GroupCount": 1,
"GroupID": 1001,
"GroupName": "Machine17"
}
],
"Status": 0
}
}
Into an object created with attributes GroupCount, GroupID and GroupName.
Here is my code:
if (request.responseStatusCode >= 200 && request.responseStatusCode < 300)
{
NSData *responseData = [request responseData];
NSError* error;
NSDictionary* jsonOverview = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSString *resultStatusString = jsonOverview[#"GetMachineOverviewResult"][#"Status"];
int resultStatus = [resultStatusString intValue];
NSDictionary *parsedObject = jsonOverview[#"GetMachineGroupsResult"];
NSMutableArray *groups = [[NSMutableArray alloc] init];
NSArray *results = [parsedObject valueForKey:#"MachineGroups"];
NSLog(#"Count %lu", (unsigned long)results.count); //results.count = 7
for (NSDictionary *parseDic in results) {
MachineGroupList *machinegrouplist = [[MachineGroupList alloc] init];
NSLog(#"%#", [parseDic class]);
NSLog(#"%#", parseDic);
for (NSString *key in parseDic) {
if ([machinegrouplist respondsToSelector:NSSelectorFromString(key)]) {
[machinegrouplist setValue:[parseDic valueForKey:key] forKey:key];
}
[groups addObject:machinegrouplist];
}
}
NSLog (#"GroupObjects %lu", (unsigned long)[groups count]); //groups count = 21
For some reason, which I cannot fathom, it parses each item three times and I end up with 21 objects instead of 7. I know it will be something simple for one of the experts here but I am new to all this and would really appreciate a helping hand here, thanks.
Edit:
Thanks a lot, here is how it now looks and it works.. The addobject was in the wrong section!
for (NSDictionary *parseDic in results)
{
MachineGroupList *machinegrouplist = [[MachineGroupList alloc] init];
NSLog(#"%#", [parseDic class]);
NSLog(#"%#", parseDic);
for (NSString *key in parseDic)
{
if ([machinegrouplist respondsToSelector:NSSelectorFromString(key)])
{
[machinegrouplist setValue:[parseDic valueForKey:key] forKey:key];
}
//[groups addObject:machinegrouplist];
}
[groups addObject:machinegrouplist];
}
NSLog (#"GroupObjects %lu", (unsigned long)[groups count]); //groups count = 7
What's happening is the following. First, lets comment out some of the last lines of code so that it looks like this:
for (NSDictionary *parseDic in results) {
//MachineGroupList *machinegrouplist = [[MachineGroupList alloc] init];
NSLog(#"%#", [parseDic class]);
//NSLog(#"%#", parseDic);
//for (NSString *key in parseDic) {
// if ([machinegrouplist respondsToSelector:NSSelectorFromString(key)]) {
// [machinegrouplist setValue:[parseDic valueForKey:key] forKey:key];
// }
// [groups addObject:machinegrouplist];
//}
}
//NSLog (#"GroupObjects %lu", (unsigned long)[groups count]); //groups count = 21
You'll se that you're iterating over 7 dictionaries, each of which has 3 objects.
Now, comment out the previous NSLog, uncomment the the inner for loop and add a NSLog inside that loop to see what you're iterating on.
for (NSDictionary *parseDic in results) {
//MachineGroupList *machinegrouplist = [[MachineGroupList alloc] init];
//NSLog(#"%#", [parseDic class]);
//NSLog(#"%#", parseDic);
for (NSString *key in parseDic) {
// if ([machinegrouplist respondsToSelector:NSSelectorFromString(key)]) {
// [machinegrouplist setValue:[parseDic valueForKey:key] forKey:key];
// }
// [groups addObject:machinegrouplist];
NSLog(#"key: %#", key);
}
}
//NSLog (#"GroupObjects %lu", (unsigned long)[groups count]); //groups count = 21
You are iterating over the 3 objects of each of the 7 dictionaries and since you're adding each object to groups outside of if ([machinegrouplist respondsToSelector:NSSelectorFromString(key)]) you end up adding 21 to groups
Cheers.