2

I am using the following JSON: http://www.kb.dk/tekst/mobil/aabningstider_en.json When I try to parse it by the key "location" as such:

//    get response in the form of a utf-8 encoded json string
NSString *jsonString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];

//    get most parent node from json string
NSDictionary *json = [jsonString JSONValue];

//    get key-path from jason up to the point of json object
NSDictionary *locations = [json objectForKey:@"location"];

NSLog( @"%@", locations );

//    iterate through all of the location objects in the json
for (NSDictionary *loc in locations )
{

    //        pull library name from the json object
    NSString *name = [loc valueForKey:@"name"];
    //        add library data table arrays respectively
    [ libraryNames addObject: ( ( name == nil | name.length > 0 ) ? name : @"UnNamed" ) ];

}

When I print the the object locations via NSLog:

{
address = "Universitetsparken 4, 3. etage, 2100 K\U00f8benhavn \U00d8";
desc = "";
lastUpdated = "";
latlng = "55.703124,12.559596";
link = "http://www.farma.ku.dk/index.php?id=3742";
name = "Faculty of Pharmaceutical Sciences Library";
parts =     {
    part =         {
        hour =             {
            day = "5.June Constitution Day (Denmark)";
            open = Closed;
        };
        hours =             {
            hour =                 {
                day = Friday;
                open = "10-16";
            };
        };
        name = main;
    };
};
}

Which is only the last value for the "location" keys. Am I doing something wrong? I tried validating the JSON via http://jsonlint.com/, however when I'd put in the JSON URL as above, it said "valid" - still only the last "locations" key was shown", however if I copy-paste it, it will not validate the JSON, and has to be fixed by removing new-lines from the string.

Also, when i try to parse the JSON and get the "name" fields, I get the following exception:

2012-05-08 15:37:04.941 iPhone App Tabbed[563:f803] *** Terminating app due to uncaught         exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x68bfe70> valueForUndefinedKey:]:     this class is not key value coding-compliant for the key name.'
*** First throw call stack:
(0x13dc052 0x156dd0a 0x13dbf11 0x9d2f0e 0x941841 0x940ca9 0x4593 0xf964e 0x114b89 0x1149bd     0x112f8a 0x112e2f 0x1148f4 0x13ddec9 0x365c2 0x3655a 0x25b569 0x13ddec9 0x365c2 0x3655a     0xdbb76 0xdc03f 0xdbbab 0x25dd1f 0x13ddec9 0x365c2 0x3655a 0xdbb76 0xdc03f 0xdb2fe 0x5ba30     0x5bc56 0x42384 0x35aa9 0x12c6fa9 0x13b01c5 0x1315022 0x131390a 0x1312db4 0x1312ccb 0x12c5879     0x12c593e 0x33a9b 0x281d 0x2785)
terminate called throwing an exception(lldb) 

It would make more sense if the "locations" tag was an array object enclosed by square brackets ([]), however right now it's only an sequence of normal key-value pairs... Sadly, that's the JSON I have to work with.

Please help and thanks a great deal! :)

Sincerely, Piotr.

Hailei
  • 42,163
  • 6
  • 44
  • 69
Piotr
  • 1,437
  • 6
  • 19
  • 24

3 Answers3

2

The JSON you've got to work with may be valid, but it doesn't make much sense. It has one big dictionary with the location key repeated many times. Most JSON parser will simply return the last value for the repeated key. It would be best if you could change the structure to use an array instead, but if you cannot there's still hope. You can read the stream and stuff the values from the location keys into an array as they come out of it. This is how you'd do that:

@interface BadJsonHelper : NSObject
@property(strong) NSMutableArray *accumulator;
@end    
@implementation BadJsonHelper
- (void)parser:(SBJsonStreamParser *)parser foundArray:(NSArray *)array {
    // void
}
- (void)parser:(SBJsonStreamParser *)parser foundObject:(NSDictionary *)dict {
    [accumulator addObject:dict];
}
@end

You can drop that little helper class at the top of your file, outside the @implementation section of the class where you're doing your work. (There's no need for the @interface and @implementation being in different files.)

In your code, you would use it like this:

BadJsonHelper *helper = [[BadJsonHelper alloc] init];
helper.accumulator = [NSMutableArray array];

SBJsonStreamParserAdapter *adapter = [[SBJsonStreamParserAdapter new] init];
adapter.delegate = helper;
adapter.levelsToSkip = 1;

SBJsonStreamParser *parser = [[SBJsonStreamParser alloc] init];
parser.delegate = adapter;

switch ([parser parse: responseData]) {
    case SBJsonStreamParserComplete: 
        NSLog(@"%@", helper.accumulator);
        break;
    case SBJsonStreamParserWaitingForData:
        NSLog(@"Didn't get all the JSON yet...");
        break;
    case SBJsonStreamParserError:
        NSLog(@"Error: %@", parser.error);
        break;
}

This example was originally adapted from the following test: https://github.com/stig/json-framework/blob/master/Tests/StreamParserIntegrationTest.m

Update: I created a fully functional example project that loads the JSON asynchronously and parses it. This is available from github.

Stig Brautaset
  • 2,602
  • 1
  • 22
  • 39
1

The JSON is valid, however there is a basic problem regarding the definition of the array of items.

Instead of defining an array of locations using brackets, the JSON redefines the same location key/value pair over and over again. In other words JSON initially says the value of location is the collection with name "The Black Diamond", but immediately after it redefines it with the collection with name "Faculty Library of Humanities" and so on till the last location Faculty of Pharmaceutical Sciences Library".

The same is true for parts and hours.

If you can't fix the result of the JSON and you really need to get it working you may want to modify the JSON removing the "location" keys and adding brackets properly.

Edit

Alternatively you may use an NSScanner and process the JSON result manually. Kinda hacky but it will work as long as the JSON format doesn't change significantly.

Edit

This snipped of code should do the work...

NSString *jsonString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];

int indx = 1;
for (;;)
{
    NSRange locationRange = [jsonString rangeOfString:@"\"location\":"];

    if (locationRange.location == NSNotFound) break;

    jsonString = [jsonString stringByReplacingCharactersInRange:locationRange
                                                     withString:[NSString stringWithFormat:@"\"location%d\":", indx++]];
} 
Tomas Camin
  • 9,996
  • 2
  • 43
  • 62
  • Cool, thanks tcamin. I thought about it, but I was hoping there would be a less invasive way to do it. Is there really no other way? – Piotr May 08 '12 at 14:06
  • Not particularly elegant but if you want to maintain this structure as much as possible you may want to rename the location keys to "location1", "location2", "location3". On the app you'll iterate location-N till objectForKey is nil – Tomas Camin May 08 '12 at 14:23
  • that's a great suggestion, how would one replace each nth occurrence of the key "location" with "location-n" where n is its occurrence number? thanks! :) – Piotr May 08 '12 at 14:45
  • check my second **Edit** Hope this helps! – Tomas Camin May 08 '12 at 15:20
  • THANK YOU tcamin! Worked like a charm! All the very best, I really appreciate it! ;) – Piotr May 08 '12 at 16:01
  • 1
    This might work, but it's a pretty hacky solution. Please see [my answer](http://stackoverflow.com/a/10543109/5950) for how to do this without resorting to hacks. (Disclaimer: I am the author of SBJson.) – Stig Brautaset May 14 '12 at 09:02
1
NSDictionary *locations = [json objectForKey:@"location"];

As you can see, the result of JSON parsing by SBJson is a NSDictionary. A dictionary contains key/value pairs, and the keys are unique identifiers for the pairs.

The JSON data you need to handle is valid but not a good one. Per RFC 4627 - 2.2:

An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.

Things like jQuery can parse the JSON also, but the result is the same as SBJson (the last one as the one). See Do JSON keys need to be unique?.

It is not a MUST, but it's still not a good practice. It would be much easier if you are able to change the structure of the JSON data on the server side (or even on the client side after receiving it) rather than parsing it as is.

Community
  • 1
  • 1
Hailei
  • 42,163
  • 6
  • 44
  • 69
  • Hi, thanks Halley. Unfortunately I should maintain the structure of the JSON as much as possible, as terrible as it may be. It's provided by my project owner, thus changing it would not be ideal. Any ideas? – Piotr May 08 '12 at 14:12
  • I agree with tcamin about using `NSScanner` if you want to manually parse the JSON as is. Another way is to fix the JSON by string operations before parsing it by SBJson. – Hailei May 08 '12 at 14:26