EzDevInfo.com

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)

Advertisements

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)

Send NSMutableArray as JSON using JSON-Framework

I'm using JSON-Framework in my project successfully to decode JSON send from a server.

Now I need to do it the other way around and I'm facing problems as the data to be sent is a NSMutableArray fetched from CoreData.

When using

NSString* jsonString = [menuItems JSONRepresentation]

I get the message "JSON serialisation not supported for MenuItems".

Do I need to convert the NSMutableArray to some other format so the JSON-Framework can serialize it?

Thanks for any help,
Miguel


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)

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)

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)

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)