smallseo.info

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)

installing json-framework with iOS

This seems like a simple-stupid thing, but I can't get it to work. Here's the flow:

Download and unzip the json-framework package from GitHub. Create a new standard, Single View Application with XCode. Make a new group named 'JSON' in my project. Make a directory in my project directory named 'JSON', and copy the files from 'json-framework-master/Classes/*' into this directory. In the XCode project, drag the files I just copied into the 'JSON' group I created. The files are successfully added to the project. In my code, I add at the top:

#include "SBJSON.h"

in the app delegate launch method, I add this:

NSDictionary *myDict = [NSDictionary dictionaryWithObject:@"Hi" forKey:@"There"];
NSString *myString = [myDict JSONRepresentation];

This is just a simple test to make sure JSON is working correctly. Everything builds and compiles fine, but I get this error:

-[__NSDictionaryI JSONRepresentation]: unrecognized selector sent to instance 0x1d537b20  

I even tried adding the '-all_load' linker flag to both the project and the target, but that does nothing. I am building on an iPhone 5 with iOS 6.0.

Also I know that iOS5+ includes native JSON support, but I need to support older versions as well.


Source: (StackOverflow)

C# de-serialise Xml to object and serialise back to Xml again

I would like to use JsonFx to convert XML to/from custom types and LINQ queries. Can anyone please provide an example to de-serialisation and serialisation back again?

Here's an example of the XML I'm working with. XML pasted here: http://pastebin.com/wURiaJM2

JsonFx Supports several strategies of binding json to .net objects including dynamic objects. https://github.com/jsonfx/jsonfx

Kind regards Si

PS I did try pasting the xml document into StackOverflow but it removed a lot of the documents quotes and XML declaration.


Source: (StackOverflow)

Parase JSON in iphone app with json-framework

i found this framewok , it seem easy to user , http://stig.github.com/json-framework/. In the exemple , he have this json :

{ "resultats":{ "joueurs":[ { "nom":"Jean Martin", "score":10000 }, { "nom":"Pierre Dupond", "score":"9000" }, { "nom":"Alice Bateau", "score":"8500" } ] } }

and he parase it like this :

NSDictionary *json    = [myJSON JSONValue];

//récupération  des résultats
NSDictionary *resultats    = [json objectForKey:@"resultats"];

//récupération du tableau de Jouers
NSArray *listeJoueur    =  [resultats objectForKey:@"joueurs"];

//On parcourt la liste de joueurs
for (NSDictionary *dic in listeJoueur) {

//création d'un objet Joueur
Joueur *joueur = [[Joueur alloc] init];

//renseignement du nom
joueur.nom = [dic objectForKey:@"nom"];

//renseingement du score
joueur.score = [[dic objectForKey:@"score"] intValue];

But me ,i don't have array in my JSON . This is my json :

{"escarrival":"NCE","escdepart":"DJE","estarrival":"08.24","estdepart":"06.27","flynumber":"TU 0286","fstatuts":"Vol atterri","proarrival":"08.25","prodepart":"06.30","realarrived":"----","realdepart":"06.27"}

How can i parase it please ? thankx


Source: (StackOverflow)

iPhone: how many objects should I bring back from webservice?

I am using a Rails webservice and was wondering how many json objects I should bring back on the first call?

Options:

  1. Bring back 200 webservice but only show 25 in the uitableview w/ Load more feature?
  2. Bring back 25 and on clicking load more fetch another 25 from webservice?
  3. ????

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)

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)

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)

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)

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)

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)

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)

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)