Writing JSON using SBJSON - iphone

I have recently started parsing JSON documents using SBJSON Parser, and I am able to read JSON documents just fine. However I am unable to figure out how I am meant to write JSON using this library. Under the documentation
http://stig.github.com/json-framework/api/3.0/interfaceSBJsonStreamWriter.html
There is a class for writing JSON, but I cannot figure out how to use it. There are no tutorials in his documentation on how to use it, and I can't find any tutorials online about using it.
As an example, I tried doing something like this
SBJsonStreamWriter *write = [[SBJsonStreamWriter alloc]init];
[write writeObjectOpen];
[write writeString:#"Testing"];
[write writeObjectClose];
But I don't know how to print this out, and I need to be able to write JSON for my project as I will be updating JSON files, so need to understand how to write JSON.
As anyone used this library before to write? If so could you please show me a quick example of how it is done
Thanks in advance!
Note: I can't use the in built JSON Parser released with new xCode as my app must be able to support phones from IOS 4+ and the new Parser won't work on phones that do not have IOS 5 installed
EDIT
Example say I wanted to create a JSON file which consisted of an array of names e.g.
{
"name":[
"Elliot Jacobs",
"Paul",
"Maria",
"Richard",
"Ana"
]
}
EDIT 2:
Example two
{
"HomeScreen":{
"Title":{
"Name":"James Bond",
"Number":"07789 123 456"
}
}
}

I'm not quite sure what you mean by 'writing JSON' so I assume that you need to construct a JSON-formatted string. Are you certain that you must use the stream writer? If not, here's an example with strings:
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
NSDictionary *command = [NSDictionary dictionaryWithObjectsAndKeys:
#"string1", #"key1",
#"string2", #"key2",
nil];
NSString *jsonCommand = [writer stringWithObject:command]; // this string will contain the JSON-encoded command NSDictionary

Related

Best way to check existent data in the database (iOS)

I'm developing an app that manages messages, and I want the app connects to the server, get messages and save them in the database(coredata). If the messages already exist, doesnt do anything and if they dont, add them to the database.
I'm thinking some ways to do it but I don't know exactly what to do. Any help? Thanks in advance
I would recommend using Restkit framework http://restkit.org
Reskit provides integration with Core Data.
Pros of using Restkit:
- Combines HTTP request/responses API, along with object mapping, offline/caching support with Core Data, all in one framework
- Object Mapping means that you're writing clean code, you define your classes and how they map to the JSON attributes, then you GET/POST/DELETE with few lines of code after that
- Core Data support means that your projects can work offline, data is sync when working online, but persistent when you need it offline
- The framework is well maintained
Cons:
- Works only with JSON REST APIs
- There can be a steep learning curve for some aspects
- Can be challenging if you work with REST APIs that are not completely 'standard'
The simplest way is to add a guid attribute (an identifier of type NSString, for example) to the entity you are interested in and check for that guid when you import data.
Here, you have two ways: let the server generate the guid for you or implement your own algorithm in the client side (iPhone, iPad, etc.). In both cases you need to be sure the guid is unique for each message.
So, for example, suppose the server generates the messages (and each message has its own guid). When you import data you also save the guid for each message object. If you have already a message with a specific guid, you don't add it, otherwise you add it. This could be done using the Find-or-Create pattern (see Implementing Find-or-Create Efficiently).
Hope that helps.
This is simple, it took me sometime to learn this, I use it in most of my apps.
First you need an ID of the fetched item, for example messageID.
When you fetch the JSON with all the items, for example using AFNetworking, you're going to receive an array of objects in NSDictionaries.
Before parsing the item load all the IDs of your stored items in a NSMutableDictionary (key => messageID, value objectID, this is related to the Core Data fault).
Don't forget to init the NSMutableArray somewhere:
_dictionaryOfEventIDAndObjectID = [NSMutableDictionary dictionary];
- (void)prepareDictionaryOfMessageIDs
{
[self.dictionaryOfEventIDAndObjectID removeAllObjects];
NSError *error = nil;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Message"];
[fetchRequest setResultType:NSDictionaryResultType];
NSExpressionDescription *objectIDDescription = [[NSExpressionDescription alloc] init];
objectIDDescription.name = #"objectID";
objectIDDescription.expression = [NSExpression expressionForEvaluatedObject];
objectIDDescription.expressionResultType = NSObjectIDAttributeType;
[fetchRequest setPropertiesToFetch:#[objectIDDescription, #"messageID"]];
NSArray *objectsDict = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
for (NSDictionary *objectDict in objectsDict) {
[self.dictionaryOfMessageIDAndObjectID setObject:[objectDict valueForKeyPath:#"objectID"] forKey:[objectDict valueForKeyPath:#"messageID"]];
}
}
Then in the fetched data completion block just add something like this:
for (NSDictionary *objectDict in objectsDict) {
NSString *fetchedID = [objectDict objectForKey:#"id"];
if ([self.dictionaryOfMessageIDAndObjectID objectForKey:fetchedID]) {
continue;
}
[self parseMessageFromDictionary:objectDict];
}

How to get some values from json saved in nsstring?

My WS returns simple json like this:
{
"thumbnail_url": "http://something.com/photos/003/582/test-tiny.jpg?1321956139",
"success": true,
"photo_url": "http://something.com/photos/003/582/test-medium.jpg?1321956139",
"big_photo_url": "http://something.com/photos/003/582/test-big.jpg?1321956139"
}
I get this in NSData from NSURLConnection. I know how to make NSString from NSData. I would like to get value for "photo_url" key.
How can it do this?
You have to use SBJSON framework to get value of photo_url.
in SBJSON framework have one method that return NSMutableDictionary For String.
You can use like this [string JSONValue] that will return NSMutableDictionary.
After that use will be get value from this code [dict valueForKey:#"photo_url"]
Thanks,
MinuMaster
Use TouchJSON or SBJson parser to parse this.
For iOS 5 only you can use the built in NSJSONSerialization class.
If you need to support iOS4 then JSONKit is a good solution.
You can then query your results like a normal dictionary.

Parse XML in iPhone (attributed not separated)

Is there a way to parse an XML in iOS where the attribute are not separated
e.g:
Users
UserId="1" Name="John Smith" Loc="London"
UserId="2" Name="Johnny Cash" Loc="Nashville"
Users
Thanks
It seams like you havent got xml at all. You are missing all usefully symbols that would normally help with the parsing. You taks is to parse a new format specification.
My first bit of advice is to ask whoever is providing you with this feed to put it into a proper format (JSON or plist are the easiest to work with).
Failing this, if the feed is not too big (otherwise you will hit performance issues), parse the feed manually character by character. You probably want to write a event based parser.
Split the feed line by line, perhaps using componentsSeparatedByString:
Then read characters into a string untill you hit an = that string is your key. Next read between the quotes "" That string is your value. FIre the key and the value off to a delegate.
JSON parsing classes will help you out...
NSString *responseString = #""; // your data contained string.
SBJSON *json = [[SBJSON new] autorelease];
NSArray *resultData = [json objectWithString:responseString error:&error];

Sending array through email on iphone

Hey guys I need to send the content of an NSMutableArray through email. I have a mailing function but I'm not sure on how to place the content of the array into a NSString to be displayed on the email under each other. Is there a way to place all the content of the array into the string with maybe HTML nextline command between each array element?
NSString *emailBody = #"Need to put the body here";
Thanks
I'll suggest you convert your array into a text string using JSON. Then place the text in the email, send it away and use JSON on the receiving end to reconstruct the array.
You can get an iPhone version of JSON called TouchJSON here.
Claus
This process is known as serialization. Apple has a guide for it, that's worth reading through.
The simplest way is to call the array's description method which will return a human readable plist in a NSString.
If you need to reconstitute the array from the email. You will need save the array as xml plist using the writeToFile: method. Then read the file back in as a string. To reconstitute you will need to extract the xml from the email, put it in a NSString, write that to file, then read it back into an NSArray.
(IIRC, there used to be a way to write to NSString as if it was a file but I can't remember how to do it anymore. Probably, writing to a NSFileHandle and reading it back instantly.)
Edit:
Can you please explain more on the
array's description method please.
Like so:
NSArray *myArray=[NSArray arrayWithObjects:#"Obj1",#"Obj2",#"Obj3",nil];
NSLog(#"myArray=%#",[myArray description]);
...prints:
myArray=(
Obj1,
Obj2,
Obj3
)
For your project you can do:
NSString *arrayString=[myArray description];
The is also a descriptionWithLocale that will print the array in different languages. I don't have a ready example for that. See NSArray, NSLocale and The Locales Programming Guide

get element value

I have a NSString like that? (in iPhone application)
NSString *xmlStr = "<?xml version=1.0 encoding=UTF-8>
<information>
<name>John</name>
<id>435346534</id>
<phone>045635456</phone>
<address>New York</address>
</information>"
How I can get elements value?
(Do i need convert to XML format and get elements value? or split string? any way please tell me?)
Thank you guys.
If you want to use split string, you can use tokenization of strings using "componentsSeparatedByString" method. This is a more cumbersome method of course, rather than the recommended XMLParser
To get the name.
NSArray *xmlStr_first_array = [xmlStr componentsSeparatedByString: #"<name>"];
NSString *xmlStr_split = [NSString stringWithFormat:#"%#",[xmlStr_first_array objectAtIndex:1]];
NSArray *xmlStr_second_array = [xmlStr_split componentsSeparatedByString: #"</name>"];
NSString *name = [NSString stringWithFormat:#"%#",[xmlStr_second_array objectAtIndex:0]];
The most obvious solution is to use an XML parser to retrieve the values from each element.
You could use the excellent TBXML for this task. It provides a really simple interface where it wouldn't take more than a few lines to retrieve the desired values. The drawback to using this small library is that it (as far as I know) loads the entire XML data into memory. In this particular case, however, that is not problem at all.
There's of course also the option of using the NSXMLParser, though this is an event-driven parser, and thus a bit less simple to use.
Your string is in xml format already and you need to parse it to retrieve data. There're several options available - for example you can use NSXMLParser class or libxml library.
Edit: XMLPerformance sample project shows how to use both approaches and compare their performance.