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

objective-c json-framework: How to parse dates, nulls, and everything else in between efficiently?

Scenario: Ruby on Rails app that returns JSON to an iOS application using json-framework to parse the JSON and push the data onto Core Data objects.

Problem: Many of attributes returned from in the JSON can be null and a large number of them are not simple strings (e.g., they are DateTimes with timezones, integers, floats, etc...).

Question: What is the most efficient way to handle such JSON? Does json-framework (or something else perhaps) have any helpers to make parsing such data easier ... -or- ... do I simply gotta do [NSNull null] checks on each and every attribute and if not null do the appropriate conversion to NSDate, NSNumber or whatever?

Thanks -wg


Source: (StackOverflow)

trouble with parsing json

i'm new in the iphone and json world . i have this json structure . You can see it clearly by putting it here http://jsonviewer.stack.hu/ .

 {"@uri":"http://localhost:8080/RESTful/resources/prom/","promotion":[{"@uri":"http://localhost:8080/RESTful/resources/prom/1/","descrip":"description
 here","keyid":"1","name":"The first
 name bla bla
 ","url":"http://localhost/10.png"},{"@uri":"http://localhost:8080/RESTful/resources/promo/2/","descrip":"description
here","keyid":"2","name":"hello","url":"http://localhost/11.png"}]}

i want to parse it with json-framework . I tried this

 NSDictionary *json    = [myJSON JSONValue];
            NSDictionary *promotionDic    = [json objectForKey:@"promotion"];
            NSLog(@" res %@ : ",[promotionDic objectAtIndex:0]); 

But then how to do to get for exemple , the name of the object at index 0 ? I think i should put object in an NSArray ? but i dont find how :/ and i dont the number of object is variable . Help please .


Source: (StackOverflow)

iPhone JSON Framework not parsing JSON string object not within an object or array

I'm using the JSON framework in Obj-C (iOS) to parse responses from a RESTful webservice (C#/.NET).

The framework is fine when it comes to arrays or objects, but one of the service calls is returning a string:

Raw value (in memory on the server): 41SIdX1GRoyw1174duOrewErZpn/WatH

JSON value in the http response once encoded by WCF: "41SIdX1GRoyw1174duOrewErZpn\/WatH"

This is processed OK by counterpart JSON frameworks on Android, Windows Phone 7 and, of course, jQuery. The server also sometimes returns a .NET WebFaultException, which would automatically serialize an error message as "Error message here".

The JSON Framework comes back with an error: Token 'string' not expected before outer-most array or object

Anyone know how can I decode a javascript string in Objective C?

thanks Kris


Source: (StackOverflow)

JSON-Framework Parsing data in a strange order

I currently have an ordered JSON string being passed into my iPhone app, which is then being parsed using the JSON Framework.

The data is as follows:

"league_table": object{
"Premiership": array[6],
"Championship": array[6],
"Division 1": array[6],
"Division 2": array[6],
"Division 3": array[6]
}

However when it parses that, it throws out a weird order.

Division 2
Division 1
Championship
"Division 3"
Premiership

Which I got by calling : NSLog(@"%@",[dictionaryValue allKeys]);.

Has anyone experienced this before? Any idea what to do to sort it again?

UPDATE ::

The shortened UN-Parsed JSON is here :

{"league_table":
{
"Premiership":[],
"Championship":[],
"Division 1":[],
"Division 2":[],
"Division 3":[]}
}

As far as I can tell, this is a Key/Value Pair, so it should be parsed in the same order. For instance going to http://json.parser.online.fr/ and pasting that in will parse it in the correct order. However the JSON-Framework doesn't parse it the same, it parses it in a strange order with no real sorting going on


Source: (StackOverflow)

Error on JSON framework parsing

I'm having a problem on parsing a JSON from Google Places.

I have the following code for parsing it:

NSString *myRawJson = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search/json?location=-15.815347,-47.9164097&radius=500&types=bank&sensor=true&key=AIzaSyBLY-lBALViJ6ybrgtOqQGhsCDQtsdKsnc"]];

    if ([myRawJson length] == 0) {
        [myRawJson release];
        return;
    }

    SBJSON *parser = [[SBJSON alloc] init];

    list = [[parser objectWithString:myRawJson error:nil] copy];

    NSDictionary *results = [myRawJson JSONValue];

    placesLatitudes = [[NSMutableArray alloc] init];
    NSDictionary *latslngs = [[results objectForKey:@"results"] valueForKey:@"location"];
    NSArray *teste = [latslngs objectForKey:@"location"];

    for (NSDictionary *element in teste)
    {
        NSString *latitude = [element objectForKey:@"lat"];
        NSLog(@"%@", latitude);
    }

    [parser release];

The URL request returns the following JSON:

{
   "html_attributions" : [ "Listagens por \u003ca rel='nofollow' href=\"http://www.telelistas.net/\"\u003eTelelistas\u003c/a\u003e" ],
   "results" : [
      {
         "geometry" : {
            "location" : {
               "lat" : -15.8192680,
               "lng" : -47.9146680
            }
         },
         "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
         "id" : "1a01f2887f1a70bd430d6a7ffa2a7e46974a1cb7",
         "name" : "Banco Bradesco S/A",
         "reference" : "CnRqAAAAXr_6FCDMlpeVF-E0b3cDxNFGzmS1bYBBGc4v4lKrcusGQPEnx1MXnCJVb3nCVWalu2IOwN9oSVtcXS6_W8JLL_CMhKzkm75UqGt5ShX_s0d4coxOBYsbo66JP1NpF9c5Ua7OxyjepQferD6SbAIjIhIQZ6qcgQT8hqAXtFTuPzuZThoUhrCcxKMRwZq2vl8Sv8LJes7d-no",
         "types" : [ "bank", "finance", "establishment" ],
         "vicinity" : "CRS 511 Bl B s/n lj 15/21 - Brasília"
      },
      {
         "geometry" : {
            "location" : {
               "lat" : -15.8177890,
               "lng" : -47.9126370
            }
         },
         "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
         "id" : "e2c56c8ca6643e0f0cef6bd0405fd8c6a30850ad",
         "name" : "UNIBANCO-União de Bancos Brasileiros S/A",
         "reference" : "CpQBgQAAABkp74S1WF0LfZEhkNj6TUbmiPu2djL81IDnFMJhRR2HDx7336PlRh46q16FwCao290T1smo1wNsGQ-sRVZ_S-MClYUDQzdpaTdNVty0JHBjQTEOMVo0yW8Uzd_OcuI12v8eZ81wu5V7sgHomBw-SeE-mhrPntOU1EzmOANNhIDRExdKmrof2hIKHdLJJaccdRIQeQ9uN-L66Ztmz4_2dkk7DhoUZxcYaZqXgXXnAwWB97e6bNCNp8A",
         "types" : [ "bank", "finance", "establishment" ],
         "vicinity" : "Bl CRS 510 Bl A s/n - Brasília"
      }
   ],
   "status" : "OK"
}

I'm trying to get the information in the path results > geometry > location > lat but I with the code above I get the error: -[__NSArrayI objectForKey:]: unrecognized selector sent to instance 0x5a526e0.

Someone know how to parse this data using JSON Framework for iOS? Thanks!


Source: (StackOverflow)

Core Data mishandles NSCFBoolean?

I've got a Core Data managed object that has an attribute with a "Boolean" type.

In my header file I've got this: @property (nonatomic, retain) NSNumber * includeInHistory;

and I'm using a @dynamic includeInHistory implementation

When interacting with an instance of this managed object before saving to disk, I've got something that actually maps to a NSCFBoolean through the NSNumber interface. I'm using "json-framework" to encode some dictionary containing values coming from Core Data.

The problem is that after saving and retrieving the data back, includeInHistory returns what appears to be a standard NSNumber (integer, not typed as Boolean). This is problematic as when converted to JSON it maps to "includeInHistory" : 1 instead of includeInHistory" : true

For now, I've had to resort to unboxing, then reboxing everytime I'm about to export as JSON, but this seems like a bug to me.... Am I missing something here ?

Thanks


Source: (StackOverflow)

Access nested arrays and dictionaries generated by JSON-framework iPhone

I'm using a Google API to return some JSON, which i have converted to their Objective C types using the JSON-framework (Stig B - Google Code).

I now have structures like this:

responseData
    results
        [0]
            title = "Stack Overflow"
    cursor

How can i access the nested array results to get at the title value (dictionary i'm guessing)?

I have tried this but no success:

    for (NSString *key in [jsonObjects objectForKey:@"responseData"]) {
        NSLog(@"%@",key);
        for (NSString *element in [key valueForKey:@"results"]) {
            NSLog(@"%@",element);   
        }
    }

The outer loop will print out the names of the arrays results and cursor so that works, but for the inner loop, I get a not key value coding compliant error.

Thanks


Source: (StackOverflow)

Unexpected end of input with SBJson in Objective-C

I have the following code that is trying to parse a JSON that I am returning from a website:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

     [connection release];

     NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

     NSLog(@"my ns string = %@", responseString);

     [responseData release];

     NSError *error; 
     NSDictionary *dictionary = [parser objectWithString:responseString   
                                               error:&error]; 
     while (error) { 
         NSLog(@"%@", error); 
         error = [[error userInfo] objectForKey:NSUnderlyingErrorKey]; 
     } 

     NSLog(@"%@", dictionary);


 }

I get these errors:

2011-08-01 20:16:47.273 myJSONParser[1040:b603] Connection didReceiveResponse: 
<NSHTTPURLResponse: 0x4e810f0> - application/json
2011-08-01 20:16:47.279 myJSONParser[1040:b603] Connection didReceiveData of length: 117
2011-08-01 20:16:47.359 myJSONParser[1040:b603] my ns string = 
2011-08-01 20:16:47.361 myJSONParser[1040:b603] Error Domain=org.brautaset.SBJsonParser.ErrorDomain Code=0 "Unexpected end of input" UserInfo=0x4eada30 {NSLocalizedDescription=Unexpected end of input}
2011-08-01 20:16:47.363 myJSONParser[1040:b603] (null)

I do have control over the JSON that I am trying to acquire and inside the PHP that generates the JSON I set the header like this:

header("Content-Type:application/json");
...
echo json_encode($arr);

"Unexpected end of input" leads me to believe that the JSON is somehow malformed, but JSONLint tells me its perfectly valid. What am I doing wrong? Thank you for taking the time to read through this, any advice would really be appreciated!

UPDATE:

I set the responseData like this:

NSMutableData *responseData;

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

         [responseData appendData:data];

     }

And the parser like this (in .h):

SBJsonParser *parser;

And .m:

parser = [[SBJsonParser alloc] init];

Charles Findings:

HTTP/1.1 200 OK
Date: Tue, 02 Aug 2011 03:30:14 GMT
Server: Apache
X-Powered-By: PHP/5.2.15
Transfer-Encoding: chunked
Content-Type: application/json

[{"key1":"Name","key2":"First","key3":"2011-08-13"},{"key1":"Second","key2":"test2","key3":"2011-08-13"}]

Description of the NSData received:

Printing description of data: {length = 117, capacity = 256, bytes = 0x5b7b22686f6d65223a22426c61636b62 ... 30382d3133227d5d}


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)