Can anyone tell me how to convert an NSArray to an NSData? I have an NSArray. I need to send it to an NSInputStream. In order to do that I need to convert the NSArray to an NSData.
Please help me, I'm stuck here.
Use NSKeyedArchiver (which is the last sentence of the post Garrett links):
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
Note that all the objects in array must conform to the NSCoding protocol. If these are custom objects, then that means you need to read up on Encoding and Decoding Objects.
Note that this will create a fairly hard-to-read property list format, but can handle a very wide range of objects. If you have a very simple array (strings for instance), you may want to use NSPropertyListSerialization, which creates a bit simpler property list:
NSString *error;
NSData *data = [NSPropertyListSerialization dataFromPropertyList:array format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error];
There's also an XML format constant you can pass if you'd rather it be readable on the wire.
On a somewhat related note, here's how you would convert the NSData back to an NSArray:
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data]
I used this code.
NSError *error;
NSMutableData *jsonData = [[NSJSONSerialization dataWithJSONObject:yourDemoArray
options:0 // Pass 0 if you don't care about the readability of the generated string
error:&error] copy];
Swift :
let data = NSKeyedArchiver.archivedData(withRootObject: jsonArray)
print(data)
You can do this-
NSArray *array= [NSArray array];
NSData *dataArray = [NSKeyedArchiver archivedDataWithRootObject:array];
In iOS 9+ use this please:
NSArray *array = [[NSArray alloc] init];
NSData *data = [NSPropertyListSerialization dataWithPropertyList:array format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil];
The older version of this was deprecated in iOS 8.
Swift 5
let data = try! NSKeyedArchiver.archivedData(withRootObject: array, requiringSecureCoding: true)
Related
I need to save array in core data, so i read that I can use NSData for it. So I think that I have problem with archiving.
NSMutableArray *newArray = [[NSMutableArray alloc]init];
NSData *newData = [NSKeyedArchiver archivedDataWithRootObject:newArray];
[myEntity setValue:newData forKey:#"nameOfMyData"];
And then I try to pick my array in another VIewController for filling
NSData *newdata = [NSData dataWithData:self.myEntity.nameOfMyData];
NSMutableArray *photoArray = [[NSMutableArray alloc]init];
photoArray = [NSKeyedUnarchiver unarchiveObjectWithData:newdata];
I have no crash, but in command line appear next:
[NSKeyedUnarchiver initForReadingWithData:]: data is empty;
did you forget to send - finishEncoding to the NSKeyedArchiver?
And when i try to add object to my array, it does not add
[photoArray addObject:myImage];
So myImage is creating and with it I have no trouble, but in debugger always write for photoArray:
photoArray = (NSMutableArray*) 0x00000000 0 objects
It should work. But when unarchiving the array rather use:
NSData *newdata = [NSData dataWithData:self.myEntity.nameOfMyData];
NSMutableArray *photoArray = [NSMutableArray arrayWithArray: [NSKeyedUnarchiver unarchiveObjectWithData:newdata]];
You either have objects in your array that dont conform to NSCoding protocol or you do not save your core data context (or saving is unsuccessful).
After archiving with
NSData *newData = [NSKeyedArchiver archivedDataWithRootObject:newArray];
what do you see when you check newData for nil? I suppose it is nil.
I need to send an NSArray to the server in the JSON array format. How can I convert it to JSON. This is a sample of my NSArray that I have to pass.
array([0] => array('latitude'=>'10.010490',
'longitude'=>'76.360779',
'altitude'=>'30.833334',
'timestamp'=>'11:17:23',
'speed'=>'0.00',
'distance'=>'0.00');
[1] => array('latitude'=>'10.010688',
'longitude'=>'76.361378',
'altitude'=>'28.546305',
'timestamp'=>'11:19:26',
'speed'=>'1.614',
'distance'=>'198.525711')
)`
and the required format is like this
[
{ "latitude":"10.010490",
"longitude":"76.360779",
"altitude":"30.833334",
"timestamp":"11:17:23",
"speed":"0.00",
"distance":"0.00"
},
{
"latitude":"10.010688",
"longitude":"76.361378",
"altitude":"28.546305",
"timestamp":"11:19:26",
"speed":"1.614",
"distance":"198.525711"
}
]
Any one have solution? Thanks in advance.
NSDictionary *firstJsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"10.010490", #"latitude",
#"76.360779", #"longitude",
#"30.833334", #"altitude",
#"11:17:23", #"timestamp",
#"0.00", #"speed",
#"0.00", #"distance",
nil];
NSDictionary *secondJsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"10.010490", #"latitude",
#"76.360779", #"longitude",
#"30.833334", #"altitude",
#"11:17:23", #"timestamp",
#"0.00", #"speed",
#"0.00", #"distance",
nil];
NSMutableArray * arr = [[NSMutableArray alloc] init];
[arr addObject:firstJsonDictionary];
[arr addObject:secondJsonDictionary];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
The simplest and best approach !!!
To convert NSArray or NSMutableArray into jsonString you can first convert it into NSData and then further convert that into a NSString. Use this code
NSData* data = [ NSJSONSerialization dataWithJSONObject:yourArray options:NSJSONWritingPrettyPrinted error:nil ];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
It helped me and hope it helps you as well. All the best.
I would recommend the SBJson-Framework.
Converting an NSMutableArray is as simple as NSString *jsonString = [yourArray JSONRepresentation];
Edit: Jack Farnandish is right u have to transform it into a NSDictionary before you can convert it to Json. In my example the NSMutableArray has to contain the Dictionary. The Array is only needed to create the square brackets at the beginning and the end of the string.
You can use the build in JSON functions of iOS or use an external lib e.g. JSONKit to convert your data to JSON
First You must change you structure into NSDictionary class and NSArray containing NSDictionary objects, then try JSONKit in iOS 5 serialization works better than standard NSJSONSerialization.
#import <JSONKit/JSON.h>
NSArray *array = // Your array here.
NSString *json = [array JSONString];
NSLog(#"%#", json);
JSONKit performs significantly better than SBJson and others in my own and the author's benchmarks.
Check this tutorial, JSON in iOS 5.0 was clearly explained (serailization, deserailization).
Is the service you are calling a RESTful service?
If so, I'd strongly recommend using RestKit. It does object serialization/deserialization. It also handles all the networking underpinnings. Extremely valuable, and well maintained.
i have a problem parsing my json data for my iPhone app, I am new to objective-C. I need to parse the json and get the values to proceed. Please help. This is my JSON data:
[{"projId":"5","projName":"AdtvWorld","projImg":"AdtvWorld.png","newFeedCount":"0"},{"projId":"1","projName":"Colabus","projImg":"Colabus.png","newFeedCount":"0"},{"projId":"38","projName":"Colabus Android","projImg":"ColabusIcon.jpg","newFeedCount":"0"},{"projId":"25","projName":"Colabus Internal Development","projImg":"icon.png","newFeedCount":"0"},{"projId":"26","projName":"Email Reply Test","projImg":"","newFeedCount":"0"},{"projId":"7","projName":"PLUS","projImg":"7plusSW.png","newFeedCount":"0"},{"projId":"8","projName":"Stridus Gmail Project","projImg":"scr4.png","newFeedCount":"0"}]
On iOS 5 or later you can use NSJSONSerialization. If you have your JSON data in a string you can do:
NSError *e = nil;
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
Edit To get a specific value:
NSDictionary *firstObject = [jsonArray objectAtIndex:0];
NSString *projectName = [firstObject objectForKey:#"projName"];
I would recommend using JSONKit library for parsing.
Here's a tutorial on how to use it.
You will basically end up with a dictionary and use objectForKey with your key to retrive the values.
JSONKit
or
NSJSONSerialization(iOS 5.0 or later)
I have had success using SBJson for reading and writing json.
Take a look at the documentation here and get an idea of how to use it.
Essentially, for parsing, you just give the string to the SBJsonParser and it returns a dictionary with an objectForKey function. For example, your code might look something like:
NSDictionary* parsed = [[[SBJsonParser alloc] init] objectWithString: json];
NSString* projId = [parsed objectForKey:#"projId"];
Use SBJson
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableDictionary *dicRes = [parser objectWithString:stringFromServer error:nil];
No need to use third party classes. Objective-c already includes handling JSON.
The class NSJSONSerialization expects an NSData object or reads from a URL. The following was tested with your JSON string:
NSString *json; // contains your example with escaped quotes
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments error:&error]
For more options with NSJSONSerialization see the documentation.
I am using JSONKit to parse JSON string into NSDictionary:
NSDictionary *deserializedData = [jsonString objectFromJSONString];
My question is: how can I change the dictionary values and get a changed JSON String?
I've tried to change the dictionary values:
[deserializedData setObject:[NSNumber numberWithInt:iRatings] forKey:#"ratings"];
But the app crashes in that line. What am I doing wrong?
Thanks in advance!
While the other answers are correct, what you really want in this case is:
NSMutableDictionary *deserializedData = [jsonString mutableObjectFromJSONString];
The mutableObjectFromJSONString method will create a mutable dictionary directly, which saves time and memory.
NSDictionary is an immutable dictionary, you need NSMutableDictionary to change the data. I'm not sure about JSONKit, but the built-in Cocoa JSON parser has a flag to return the data in mutable containers.
In worst case, you can do something like that:
NSMutableDictionary* data = [NSMutableDictionary dictionaryWithDictionary:[jsonString objectFromJSONString]];
[data setObject:[NSNumber numberWithInt:iRatings] forKey:#"ratings"];
//
// we begin with our string in json format
//
NSString *jsonString = [[NSString alloc] initWithString:#"{\"1\":\"Hole 1: Rossy Robinson - $25\",\"2\":\"Hole 7: Davey Ambrose - $25\",\"3\":\"Hole 14: Ross Robinson - $25\"}"];
//
// convert the json string to an NSMutableDictionary
//
NSError *e;
NSMutableDictionary *JSONdic = [NSJSONSerialization JSONObjectWithData: [jsonString dataUsingEncoding: NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &e];
//
// change a value and add a new value in the dict
//
NSLog(#"before: object for key 1 is: %#", [JSONdic objectForKey:#"1"]);
[JSONdic setObject:#"xxx" forKey:#"1"];
[JSONdic setObject:#"Phil McQuitty" forKey:#"2"];
//
//convert dictionary object to json data
//
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:JSONdic options:NSJSONWritingPrettyPrinted error:&e];
//
// convert the json data back to a string
//
NSString *jsonText = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];\
//
// print out the final results
//
NSLog(#"back to string: %#", jsonText);
You try to change an immutableobject.
NSMutableDictionary *deserializedData = [NSMutableDictionary dictionaryWithDictionary: [jsonString objectFromJSONString]];
This is a mutable dictionary and you can change the values in it.
You try like this:
NSMutableDictionary *deserializedData = [NSMutableDictionary dictionaryWithDictionary: [jsonString objectFromJSONString]];
and then change the values:
[deserializedData setObject:[NSNumber numberWithInt:iRatings] forKey:#"ratings"];
For NSDictionary we cannot add or change values, thats why application is crashing.
I'm trying to convert a NSDictionary to XML. (I was successful in transforming NSDictionary to JSON). But now I need to transform NSDictionary to XML. Is there a built-in serializer in Objective-C like the one for JSON?
int r = arc4random() % 999999999;
//simulate my NSDictionary (to be turned into xml)
NSString *name = [NSString stringWithFormat:#"Posted using iPhone_%d", r];
NSString *stock_no = [NSString stringWithFormat:#"2342_%d", r];
NSString *retail_price = #"12345";
NSArray *keys = [NSArray arrayWithObjects:#"name", #"stock_no", #"retail_price", nil];
NSArray *objects = [NSArray arrayWithObjects:name,stock_no,retail_price, nil];
NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *theFinalRequestDictionary = [NSDictionary dictionaryWithObject:theRequestDictionary forKey:#"product"];
...//other irrelevant code omitted
NSData *theBodyData = [NSPropertyListSerialization dataFromPropertyList:theFinalRequestDictionary format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];
NSPropertyListFormat format;
id XMLed = [NSPropertyListSerialization propertyListFromData:theBodyData
mutabilityOption:NSPropertyListImmutable
format:&format
errorDescription:nil];
NSLog(#"the XMLed is this: %#", [NSString stringWithFormat:#"%#", XMLed]);
The NSLog doesn't print a string in XML format. It prints it like a NSDictionary.
What should I use to serialize my NSDictionary to XML?
propertyListFromData:... returns a "property list object", that is, depending on the contents of the data, an array or a dictionary. The thing that you're actually interested in (the xml) is returned by dataFromPropertyList:... and thus stored in your theBodyData variable.
Try this:
NSLog(#"XML: %#", [[[NSString alloc] initWithData:theBodyData encoding:NSUTF8StringEncoding] autorelease]);
There are many different varieties of XML. If you're not picky about the specific tags, and if the contents of your dictionary is limited to types used in property lists (NSString, NSNumber, NSDate, etc.) you can write your dictionary to a property list in one line:
[myDict writeToFile:somePath atomically:YES];
If you'd prefer to keep the XML in memory instead of writing to a file, use NSPropertyListSerialization as you're doing.