Reputation: 942
If you had a NSString containing JSON data and you needed to retrieve the VALUE for a given KEY, but you needed to read the RAW JSON string for that key, how would you do it?
Suppose that the VALUE has several dictionaries and arrays, and you needed the raw string just to calculate a signature.
Is there anything out there that could do this? JSONKit doesn't provide this functionality. I'd like to avoid writing a custom parser just for this feature.
Upvotes: 0
Views: 646
Reputation: 593
Actually JSONKit is very good for satisfying your needs. First you should convert your string to NSData to use JSONKit to parse it, then you can find the value of the key you want, finally JSONKit can convert it back to NSString.
Some codes will show more details here, hope to help:
NSString *jsonString = @"{\"k\":{\"age\":1,\"desc\":\"something cool\"}}";
NSData *rawData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id jsonObject = [rawData objectFromJSONData];
NSLog(@"json object is:%@", jsonObject);
id kObject = [jsonObject valueForKey:@"k"];
NSLog(@"the object of key k is: %@", kObject);
NSString *kString = [kObject JSONString];
NSLog(@"raw string of k is: %@", kString);
And the output will look like:
2012-01-04 12:50:41.234 App[1966:207] json object is:{
k = {
age = 1;
desc = "something cool";
};
}
2012-01-04 12:50:41.235 App[1966:207] the object of key k is: {
age = 1;
desc = "something cool";
}
2012-01-04 12:50:41.235 App[1966:207] raw string of k is: {"age":1,"desc":"something cool"}
Upvotes: 1