EzDev.org

json-framework

JSON (JavaScript Object Notation) is a light-weight data interchange format that's easy to read and write for humans and computers alike. This framework implements a strict JSON parser and generator in Objective-C. SBJson for Objective-C :: http://sbjson.org


json-framework error in iPhone static library

I have an iPhone app that uses the json-framework. I moved some of the code, including the json-framework source, from the main project to a static library. When I did this, the json-framework stopped getting compiled into the binary (double checked with class dump). This causes a nasty error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFString JSONValue]: unrecognized selector sent to instance 0x43897f0'

Everything else in the static library continues to function properly.


Source: (StackOverflow)

How to detect JSON object/JSON Array on XCode using JSON-Framework

I have some problem with JSON parsing. When I hit URL, I've got JSON response like this:

//JSON 1
{ "data":
  {"array":
    ["3",
       {"array":
          [
            {"id":"1","message":"Hello","sender":"inot"},
            {"id":"2","message":"World","sender":"inot"},
            {"id":"3","message":"Hi","sender":"marza"}
          ]
        }
     ]
   },
 "message":"MSG0001:Success",
 "status":"OK"
}

But if the result of data is just 1, the JSON response is like this:

//JSON 2
{ "data":
  {"array":
    ["3",
       {"array":
          {"id":"3","message":"Hi","sender":"marza"}
       }
     ]
   },
 "message":"MSG0001:Success",
 "status":"OK"
}

I implement this code to get the id, message and sender value, and work fine on JSON 1, but error on JSON 2. I use JSON-Framework. And the question is how to detect that the JSON response is object ({ }) or array ([ ]) ??

// Parse the string into JSON
NSDictionary *json = [myString JSONValue];

// Get all object
NSArray *items = [json valueForKeyPath:@"data.array"];
NSArray *array1 = [[items objectAtIndex:1] objectForKey:@"array"];
NSEnumerator *enumerator = [array1 objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
   NSLog(@"id      = %@",[item objectForKey:@"id"]);
   NSLog(@"message = %@",[item objectForKey:@"message"]);
   NSLog(@"sender  = %@",[item objectForKey:@"sender"]);
}

Source: (StackOverflow)

Replace all NSNull objects in an NSDictionary

I'm curious, I currently have an NSDictionary where some values are set to an NSNull object thanks to the help of json-framework.

The aim is to strip all NSNull values and replace it with an empty string.

I'm sure someone has done this somewhere? No doubt it is probably a four liner and is simple, I am just far too burnt out to figure this out on my own.

Thanks!


Source: (StackOverflow)

JSON error on iPhone app

i am getting error when i try to run an app on my simulator. I have copied the JSON(JSON Framework) project in my app but my simulator crashes when it compiles the below lines,(I am using iOS 4.2)

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *jsonString = [NSString stringWithString:@"{\"foo\": \"bar\"}"];
    NSDictionary *dictionary = [jsonString JSONValue];
    NSLog(@"Dictionary value for \"foo\" is \"%@\"", [dictionary objectForKey:@"foo"]);
}

ERROR:

2011-03-02 13:33:37.304 test[10918:207] -[NSCFString JSONValue]: unrecognized selector sent to instance 0x3034
2011-03-02 13:33:37.308 test[10918:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString JSONValue]: unrecognized selector sent to instance 0x3034'
*** Call stack at first throw:
(
    0   CoreFoundation                      0x00da7be9 __exceptionPreprocess + 185
    1   libobjc.A.dylib                     0x00efc5c2 objc_exception_throw + 47
    2   CoreFoundation                      0x00da96fb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
    3   CoreFoundation                      0x00d19366 ___forwarding___ + 966
    4   CoreFoundation                      0x00d18f22 _CF_forwarding_prep_0 + 50
    5   test                                0x000025d7 -[testViewController viewDidLoad] + 119
    6   UIKit                               0x0035e65e -[UIViewController view] + 179
    7   test                                0x0000237e -[testAppDelegate application:didFinishLaunchingWithOptions:] + 79
    8   UIKit                               0x002b11fa -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1163
    9   UIKit                               0x002b355e -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 439
    10  UIKit                               0x002bddb2 -[UIApplication handleEvent:withNewEvent:] + 1533
    11  UIKit                               0x002b6202 -[UIApplication sendEvent:] + 71
    12  UIKit                               0x002bb732 _UIApplicationHandleEvent + 7576
    13  GraphicsServices                    0x016dda36 PurpleEventCallback + 1550
    14  CoreFoundation                      0x00d89064 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
    15  CoreFoundation                      0x00ce96f7 __CFRunLoopDoSource1 + 215
    16  CoreFoundation                      0x00ce6983 __CFRunLoopRun + 979
    17  CoreFoundation                      0x00ce6240 CFRunLoopRunSpecific + 208
    18  CoreFoundation                      0x00ce6161 CFRunLoopRunInMode + 97
    19  UIKit                               0x002b2fa8 -[UIApplication _run] + 636
    20  UIKit                               0x002bf42e UIApplicationMain + 1160
    21  test                                0x0000230c main + 102
    22  test                                0x0000229d start + 53
)
terminate called after throwing an instance of 'NSException'
Program received signal:  “SIGABRT”.
(gdb) 

Source: (StackOverflow)

Parse JSON data using Asihttprequest and the Json framework for iphone

I've been learning how to parse JSON using the JSON framework and ASIHTTPRequest for iOS. I've tested using twitter feeds and also a custom feed through a community tutorial. All is going well.

I then thought I'll test using the Microsoft Odata Service for Northwind db. You can view the json results here:

http://jsonviewer.stack.hu/#http://services.odata.org/Northwind/Northwind.svc/Products%281%29?$format=json

Now I've struggling to work out how to parse just the product name. Can anyone point me in the right direction?

On my requestFinished i have this:

- (void)requestFinished:(ASIHTTPRequest *)request
{    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    NSString *responseString = [request responseString];
    NSDictionary *responseDict = [responseString JSONValue];

    //find key in dictionary
    NSArray *keys = [responseDict allKeys];

    NSString *productName = [responseDict valueForKey:@"ProductName"];
    NSLog(@"%@",productName);
}

In the log I have null.

If I change the valueforKey to @"d" I get the whole of the payload but I just want the productName.

The service URL I am using is:

http://servers.odata.org/Northwind/Northwind.svc/Products(1)?$format=json


Source: (StackOverflow)

How to parse a JSON having no quotes with its KEY string?

I want to parse the json output resulting from the following url in SBJSON framework for iOS http://maps.google.com/maps?q=school&mrt=yp&sll=13.006389,80.2575&output=json

while(1);{title:"school - Google Maps",url:"/maps?q=school\x26mrt=yp\x26sll=13.006389,80.2575\x26ie=UTF8\x26hq=school\x26hnear=",urlViewport:false,ei:"RCu3T4eeMqSiiAe7k-yZDQ",form:{selected:"q",q:{q:"school",mrt:"yp",what:"school",near:""},d:{saddr:"",daddr:"",dfaddr:""},geocode:""},

I am using http://www.bodurov.com/JsonFormatter/ to read it online.

In ASIHttpRequest response method I removed while(1); from the response

NSString *responseString = [[request resonseString]substringFromIndex:9]; //to remove while(1)
SBJSONParser * parser = [[SBJSONParser alloc]init];
NSDictionary *jsonDict = (NSDictionary*)[parser objectFromString:responseString];
NSLog(@"%@",jsonDict) // prints null
// [responseString JSONValue] also reports error

I guess JSON key without double quotes is causing problem.

Instead of { "title": "hospital - Google Maps", "urlViewport": false, }, we get { title: "hospital - Google Maps", "urlViewport": false }

Please help me to parse this complex JSON structure returned from Google.


Source: (StackOverflow)

Using JSON Framework on iPhone - HELP!

Currently I am using the following code to parse the JSON link sent. This is how I also send a GET call to the Google Reader API for an upcoming iPhone application of mine.

- (NSArray *)subscriptionList
{
if(!cookies && [cookies count] == 0) {
    [self requestSession];
}

NSString * url = @"http://www.google.com/reader/api/0/subscription/list?output=json&client=scroll";

ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
[request setRequestMethod:@"GET"];
[request setRequestCookies:cookies];
[request addRequestHeader:@"Authorization" value:[NSString stringWithFormat:@"GoogleLogin auth=%@", [self auth]]];

[request startSynchronous];

subfeeds = [NSMutableArray array];

// Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];

if ([request responseStatusCode] == 200) {

    NSData * sixty = [request responseData];

    NSString * body = [[NSString alloc] initWithData:sixty encoding:NSUTF8StringEncoding];
    if (body) {
        NSArray *feeds = [parser objectWithString:body error:nil];
        NSLog(@"Array Contents: %@", [feeds valueForKey:@"subscriptions"]);
        NSLog(@"Array Count: %d", [feeds count]);

        NSDictionary *results = [body JSONValue];
        NSArray *ohhai = [results valueForKey:@"subscriptions"];

        for (NSDictionary *title in ohhai) {
            subTitles = [title objectForKey:@"title"];
            NSLog(@"title is: %@",subTitles);
        }
    }
}

return subfeeds;
[subTitles release];
[parser release];
}

I can successfully parse the JSON using the above code, and it successfully outputs the titles into NSLog. In my RootViewController.m, I call the following to grab this -(NSArray *)subscriptionList.

-(void)viewDidAppear:animated {
GoogleReader * reader = [[GoogleReader alloc] init];
[reader setEmail:gUserString];
[reader setPassword:gPassString];

//feedItems is a NSArray where we store the subscriptionList NSArray
feedItems = [reader subscriptionList];

//NSString *feedTitle = [];

NSLog(@"%@", feedItems);

[reader release];
// the rest of the function
}

The code above successfully works with the credentials entered. As you can see there is also a commented NSString called feedTitle. This is where I want to pull the @"title" from the parsed JSON but I do not know how to call it.

Any help would be greatly appreciated!

This is what the JSON source looks like:

{"subscriptions":
[
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""},
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""},
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""},
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""},
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""}
]
}

I'm interested in only the "title" node.


Source: (StackOverflow)

How do I convert NSDecimalNumber to NSInteger?

OK, I'm using a JSON-enabled Rails web-service to provide data to an iPhone application. I'm finding my Integer values (IDs) are being interpreted by the json-framework as a NSDecimalNumber type. I need it as an integer. How can I get an integer value out of my NSDecimalNumber typed variable? I have tried everything I know, and I'm at my wits end.


Source: (StackOverflow)

What is the ideal way in the iPhone SDK to handle data coming from a web service?

Currently, we're using ASP.NET asmx web services to interface with our iPhone application.

My question is; whats the most ideal way of converting the responses from the services into objects which are easy to manage in Obj-C.

At present, we have defined a class which has all the methods in it (GetSomethingById), this then converts the JSON string to a JSON object using the json-framework. Then constructs the appropriate class with an "initWithJSON:(id)theJson" constructor.

The problem is... we seem to be at a constant battle as certain classes like to be autoreleased (therefore we have a mix of retained objects ([... retain]) and normal classes. This works perfectly but we're upsetting the Leaks tool!

I've seen a few solutions involving the use of Core Data. In summary:

  1. Consume web service
  2. "Serialize" into an appropriate data structure (class) <- This is the troublesome part

Can anyone recommend a sane solution?


Source: (StackOverflow)

json-framework: EXC_BAD_ACCESS on stringWithObject


UPDATE:

I found that the reason for the previous error was an error in the documentation.

The method should be named proxyForJson, not jsonProxyObject...

But I'm still stuck, though.

I now get an EXC_BAD_ACCESS error inside stringWithObject some where. Any clues?


UPDATE 2:

My proxyForJson implementation is a cut-n-paste from then documentation:

- (id)proxyForJson {
    return [NSDictionary dictionaryWithObjectsAndKeys:
            Navn, @"Navn",
            Adresse, @"Adresse",
            Alder, @"Alder",
            nil];
}

Trying to make json serialization work for my custom objective-c class.

As I understand the documentation, json-framework can serialize custom objects, if they implement the jsonProxyObject method.

So I have this class:

@interface MyObject : NSObject {
    NSString *Name;
    NSString *Addresse;
    NSInteger Age;
}
@property (nonatomic, retain) NSString *Name;
@property (nonatomic, retain) NSString *Addresse;
@property (nonatomic, assign) NSInteger Age;
- (id)jsonProxyObject;
@end

And I try to serialize an array with some instances in it:

[json stringWithObject:list error:&error];

But all I get is he following error:

"JSON serialisation not supported for MyObject"

I guess the jsonWriter can't find my jsonProxyObject method for some reason, buy why?

Regards.


Source: (StackOverflow)

JSON Parse Error

I am using SBJson framework (also known as json-framework) for the iOS.

When parsing a certain JSON file, I am getting the following error: -JSONValue failed. Error is: Unescaped control character [0x09]'

I have used this framework many times and I am also parsing a very similar JSON file (that is even much longer) in that same app and it's working fine.

I tried throwing around a bunch of NSLogs and everything seems to be fine. Can someone please point me to what this error means, or at least how to go ahead in debugging such an error?

Here is the code that displays the error:

- (void)downloadSchedule:(NSString *)jsonString {

    // Get JSON feed URL and instantiate a dictionary object with its content
    NSDictionary *topDic = [jsonString JSONValue];

    NSLog(@"topDic count %d", [topDic count]);

topDic is showing a count of 0. The error is at the [jsonString JSONValue] line.

Thank you


Source: (StackOverflow)

Sectioned UITable & JSON

I have been trying for days to figure out how to parse this JSON to a sectioned UITable but I am not successful, I've only been able to figure out how to get the section name, but failed to get each section row count and data for each row in each section.

Since the transportation group may vary from time to time and their name may change, so I guess I need to use allKeys to find out each section title 1st.

Please help and points me to the right direction to extract the data for a sectioned UITable, Thank you.

{
   "transport" : {
  "public" : [
     {
        "transport_id" : "2",
        "transport_name" : "Ferry"
     },
     {
        "transport_id" : "3",
        "transport_name" : "Bus"
     },
     {
        "transport_id" : "4",
        "transport_name" : "Taxi"
     },
     {
        "transport_id" : "5",
        "transport_name" : "Tram"
     }
  ],
  "Private" : [
     {
        "transport_id" : "11",
        "transport_name" : "Bicycle"
     },
     {
        "transport_id" : "12",
        "transport_name" : "Private Car"
     }
  ],
  "Misc" : [
     {
        "transport_id" : "6",
        "transport_name" : "By Foot"
     },
     {
        "transport_id" : "7",
        "transport_name" : "Helicopter"
     },
     {
        "transport_id" : "8",
        "transport_name" : "Yatch"
     }
  ]
   }
}  



NSDictionary *results = [jsonString JSONValue];

NSDictionary *all = [results objectForKey:@"transport"];
NSArray *allKeys = [all allKeys];

NSArray *transports = [results objectForKey:@"transport"];
for (NSDictionary *transport in transports)
{
    [transportSectionTitle addObject:(transport)];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [transportSectionTitle count];
}

Source: (StackOverflow)

Parsing JSON: brackets in response

I want to parse this JSON YouTube recently featured. This is how I get the title of the videos:

NSString *response = [request responseString];
    responseDict = [response JSONValue];

videoTitleArray = [responseDict valueForKeyPath:@"feed.entry.title.$t"];

And it works like I want it. But I also want to display the author of the video. But the following code for this does not work properly:

videoAuthorArray = [responseDict valueForKeyPath:@"feed.entry.author.name.$t"];
    NSLog(@"%@", videoAuthorArray);

The list of the authors I get looks like this:

(
    author 1
),
    (
    author 2
),
    (
    author 3
),
    (
    author 4
),

I can't display the names in for example a table view because of the brackets. How can I display the author names like the video titles?


Source: (StackOverflow)

json-framework - Token 'start of array' not expected after outer-most array or object

Feeding the json-parser with the this data: http://mapadosradares.com.br/api/get_initial_load yields this error: Token 'start of array' not expected after outer-most array or object

Here is my code:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSLog(@"Connection didReceiveData of length: %u", data.length);

    // Printing the received data
    size_t length = [data length];
    unsigned char aBuffer[length];
    [data getBytes:aBuffer length:length];
    //aBuffer[length - 1] = 0;
    NSLog(@"\n\n\n\n%s\n\n\n\n", aBuffer);

    SBJsonStreamParserStatus status = [parser parse:data];

    if (status == SBJsonStreamParserError) {
        NSLog(@"Parser error: %@", parser.error);

    } else if (status == SBJsonStreamParserWaitingForData) {
        NSLog(@"Parser waiting for more data");
    }
}

As far as I can tell the JSON is perfectly fine. Any thoughts?

UPDATE:

Here's the parser initalization:

- (void) getInitialLoad
{
    adapter = [[SBJsonStreamParserAdapter alloc] init];
    parser = [[SBJsonStreamParser alloc] init];

    adapter.delegate = self;
    parser.delegate = adapter;

    NSString *url = @"http://mapadosradares.com.br/api/get_initial_load";
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy    timeoutInterval:60.0];
    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

Source: (StackOverflow)

JSON framework error

I am trying to run the salesforce ios phonegap app for mobile sdk project named

https://github.com/forcedotcom/SalesforceMobileSDK-iOS/tree/master/hy...

The app starts but stops with the Exception:

2012-01-09 17:18:15.897 VFConnector[1354:207] -[NSCFString JSONValue]: 
unrecognized selector sent to instance 0x5aac9b0 
2012-01-09 17:18:15.916 VFConnector[1354:207] *** Terminating app due 
to uncaught exception 'NSInvalidArgumentException', reason: '- 
[NSCFString JSONValue]: unrecognized selector sent to instance 
0x5aac9b0' 
*** Call stack at first throw: 
( 
        0   CoreFoundation                      0x01a775a9 
__exceptionPreprocess + 185 
        1   libobjc.A.dylib                     0x01bcb313 
objc_exception_throw + 44 
        2   CoreFoundation                      0x01a790bb - 
[NSObject(NSObject) doesNotRecognizeSelector:] + 187 
        3   CoreFoundation                      0x019e8966 ___forwarding___ + 
966 
        4   CoreFoundation                      0x019e8522 
_CF_forwarding_prep_0 + 50 
        5   VFConnector                         0x00004af3 - 
[SalesforceOAuthPlugin populateOAuthProperties:] + 99 
        6   VFConnector                         0x00003a8d - 
[SalesforceOAuthPlugin authenticate:withDict:] + 365 
        7   VFConnector                         0x0001772b -[PhoneGapDelegate 
execute:] + 434 
        8   VFConnector                         0x00002d67 - 
[SFContainerAppDelegate execute:] + 71 
        9   VFConnector                         0x00017150 -[PhoneGapDelegate 
executeQueuedCommands] + 265 
        10  VFConnector                         0x000171fd -[PhoneGapDelegate 
flushCommandQueue] + 81 
        11  VFConnector                         0x0001756c -[PhoneGapDelegate 
webView:shouldStartLoadWithRequest:navigationType:] + 822 
        12  VFConnector                         0x00003060 - 
[SFContainerAppDelegate 
webView:shouldStartLoadWithRequest:navigationType:] + 96 
        13  UIKit                               0x004bea92 -[UIWebView 
webView:decidePolicyForNavigationAction:request:frame:decisionListener:] 
+ 291 
        14  CoreFoundation                      0x019e7c7d __invoking___ + 29 
        15  CoreFoundation                      0x019e7b51 -[NSInvocation 
invoke] + 145 
        16  CoreFoundation                      0x01a15858 -[NSInvocation 
invokeWithTarget:] + 72 
        17  WebKit                              0x025d8c76 - 
[_WebSafeForwarder forwardInvocation:] + 182 
        18  CoreFoundation                      0x019e8a04 ___forwarding___ + 
1124 
        19  CoreFoundation                      0x019e8522 
_CF_forwarding_prep_0 + 50 
        20  CoreFoundation                      0x019e7c7d __invoking___ + 29 
        21  CoreFoundation                      0x019e7b51 -[NSInvocation 
invoke] + 145 
        22  WebCore                             0x030cc150 
_ZL20HandleDelegateSourcePv + 64 
        23  CoreFoundation                      0x01a588ff 
__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15 
        24  CoreFoundation                      0x019b688b 
__CFRunLoopDoSources0 + 571 
        25  CoreFoundation                      0x019b5d86 __CFRunLoopRun + 
470 
        26  CoreFoundation                      0x019b5840 
CFRunLoopRunSpecific + 208 
        27  CoreFoundation                      0x019b5761 CFRunLoopRunInMode 
+ 97 
        28  GraphicsServices                    0x021141c4 GSEventRunModal + 
217 
        29  GraphicsServices                    0x02114289 GSEventRun + 115 
        30  UIKit                               0x00335c93 UIApplicationMain 
+ 1160 
        31  VFConnector                         0x00002777 main + 135 
        32  VFConnector                         0x000026e5 start + 53 
        33  ???                                 0x00000001 0x0 + 1 
) 
terminate called after throwing an instance of 'NSException' 

Please Help because I am stuck on this for 2 days!


Source: (StackOverflow)