Store an NSArray into a KeychainItemWrapper - ios

I have to store an NSArray (which contains NSString and BOOL) into a KeychainItemWrapper to re use it in another ViewController, and to keep it in memory even if the app is closed.
I've already see at this question but it won't help me, because I can't find the SBJsonWriter files.
Can anyone could help me please ?
Thanks a lots.
Have a good day !

SBJsonWriter is a 3rd party JSON library popular years back, now iOS has this built in.
Serialize the data as JSON using the native NSJSONSerialization, and then write it to the keychain (assuming kSecValueData, which is encrypted):
NSArray* array = ...;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:array options:0 error:nil];
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[keychainItem setObject:jsonString forKey:(__bridge id)kSecValueData];
To read the data back to an NSArray:
NSString* jsonString = [keychainItem objectForKey:(__bridge id)kSecValueData];
NSArray* array = nil;
if(jsonString.length > 0)
{
id jsonObject = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
// Type check because the JSON serializer can return an array or dictionary
if([jsonObject isKindOfClass:[NSArray class]])
array = jsonObject;
}
// use your array variable here, it may be nil

You can use Apple's NSJSONSerialization class to do what your linked answer is using SBJsonWriter to do.
Example:
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:0 error:&error];
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
Then write the jsonString to your keychain.
To reverse the process, retrieve the jsonString from your keychain and do this:
NSArray* myArray = [NSJSONSerialization JSONObjectWithData:jsonString options:0 error:&error];

Related

How to store & retrieve NSArray object in sqlite database in objective c

I want to store & retrieve NSArray object in single column of sqlite database.
Does anyone knows how i can achieve that?
The easiest way to achieve this is convert the array to JSON string and store the string in database and while fetching the data convert the JSON string to array again.
Array to JSON
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arrayObject options:NSJSONWritingPrettyPrinted error:nil]
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
JSON to Array
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *arrayObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
It's many way to do this. One of the simple is use componentsJoinedByString method.
NSArray* someArray = #[.....];
NSString* result = [someArray componentsJoinedByString:#"<some separator>"];
Also you can NSKeyedArchiver
NSArray* someArray = #[.....];
NSData* dataToSave = [NSKeyedArchiver archivedDataWithRootObject:someArray];
But you will provide object in array that confirm to the NSCoding protocol.
Also you can use json serialisation:
NSArray* someArray = #[.....];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:someArray options:NSJSONWritingPrettyPrinted error:nil]

How to convert data string to json object and string in iOS?

How to convert string to JSON object or JSON array in iOS?
my JSON string Like That.
{"Data": [{"ID":"1","Name":"Raj"},{"ID":"2","Name":"Rajneesh"}]}
I want to get ID or Name from this string please help me if anyone now this.
Thank You.
I try below code but print null
NSString *JsonString=#"{"Data": [{"ID":"1","Name":"Raj"},{"ID":"2","Name":"Rajneesh"}]}";
NSData *objectData = [JsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:0 error:&error];
NSArray* array = [json objectForKey:#"Data"];
NSLog(#"Print Array %#",array);
Use this
NSString *str=#"{\"Data\": [{\"ID\":\"1\",\"Name\":\"Raj\"},{\"ID\":\"2\",\"Name\":\"Rajneesh\"}]}";
NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
NSMutableArray *dataArr=[dict valueForKey:#"Data"];
for (NSDictionary *userData in dataArr) {
NSLog(#"Id:%# Name:%#",[userData valueForKey:#"ID"],[userData valueForKey:#"Name"]);
}
Always Remember that when there are { } curly brackets, it means it is Dictionary and when [ ] this, means Array
NSURL *url=[NSURL URLWithString:#"Your JSON URL"];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSArray *array = json[#"Data"];
for(NSMutableDictionary *dic in array)
{
NSLog(#"%#",dic[#"ID"]); // give 1 & 2
NSLog(#"%#",dic[#"Name"]); // Raj and Rajneesh
}
This is not the correct JSON string which can be parsed by Objective c, get string from encoder and you will get a valid string, other then that for JSON to Dictionary conversion is simple in iOS as its natively supported.
NSData *data = [strJSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];

How to JSON encode arrays in array from iOS to PHP

I try to JSON encode NSDictionary into NSArray upload to PHP web-services.
This is how I JSON encode my NSArray:
NSError * error;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:my_array_1 options:0 error:&error];
NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
jsonString = [jsonString stringByReplacingOccurrencesOfString:#"\"" withString:#"\\\""];
Then I insert this JSON String into another array by:
NSString * jsonRequest = [NSString stringWithFormat: #"{\"request\":\"syncBookmark\",\"bookmark_array\":\"%#\",\"user_id\":\"%#\"}", jsonString, user_id, nil];
NSData * requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
Before I request the webservices, the JSON encoded string is like:
{"request":"syncBookmark","bookmark_array":"[{\"PostId\":\"4\",\"last_edit_date\":\"2014-03-03 01:05:37\",\"BookmarkId\":\"1\",\"last_sync_date\":\"\",\"is_active\":\"1\"}]","user_id":"7"}
I can echo the 'user_id' in PHP which is '7' correctly, but when I check the array - is_array($bookmark_array) in PHP it just return FALSE. Am I doing the way wrongly to put arrays in array?
This is because you enter JSON string as string and it is obviously escaped by the stringWithFormat method.
You should create a NSDictionary and serialize that together. So instead of serializing my_array_1 variable, you will serialize the dictionary.
Create the dictionary:
NSDictionary* dictionary = #{ #"request" : #"syncBookmark", #"bookmark_array" : my_array_1 };
Then serialize the dictionary:
NSError * error;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
This is the correct way to serialize a JSON object, not inserting serialized objects into another string. Although I see why you wanted to do that.
Don't bother doing the stringByReplacingOccurrencesOfString stuff. Let NSJSONSerialization do all of the necessary quoting for you.
So, if you really need that jsonString as a string that your PHP will recursively un-encode, just JSON encode the array, and then put that in another dictionary and then encode that again:
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:my_array_1 options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSDictionary *dictionary = #{#"request" : #"syncBookmark",
#"bookmark_array" : jsonString,
#"user_id" : user_id};
NSData *finalData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
That should create a payload much like you said you wanted in your question.
Having said that, a more logical approach would be:
NSError *error;
NSDictionary *dictionary = #{#"request" : #"syncBookmark",
#"bookmark_array" : my_array_1,
#"user_id" : user_id};
NSData *finalData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
If that's what generated your payload, then your PHP wouldn't have to do multiple calls to json_decode.

Json values into NSArray Parsing in IOS

How to store this data in NSArray?
I'm getting JSON response in this format like this:
{
1 = USA;
4 = India;
}
I need to convert this into NSArray
If your JSON is a string, get an NSData object first:
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
Then turn it into an NSDictionary using the NSJSONSerialization class:
NSError* error = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
Since you said you want an NSArray, do the following:
NSArray *jsonArray = [jsonDict allValues];
Note that the order of the entries in the array is undefined, according to Apple's documentation. So if you need a particular order, you'll have to figure out a better approach.
This is JSON dictionary, First you convert this to NSDictionary from JSON.
NSDictionary *dictionary = //parse json using NSJSONSerilization
NSArray *array = [dictionary allValues];
allValues will return an array with all objects.
Try this:
NSString *jsonString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *dictionary =[jsonString JSONValue];
NSArray *array = [dictionary allValues];
NSLog(#"Array values = %#",array);

Conversion from object to json text ios

What i need
"sampleId":"[{\"TextVal\":\"10233\"}]"
Where i have
NSDictionary *sampledict=#{#"TextVal": #"10233"};
NSArray *arr=[NSArray arrayWithObject:sampledict];
[dict setObject:arr forKey:#"sampleId"];
But converting this to json text gives me
"sampleId":[{TextVal:10233}]
is there a way to get the value as {\"TextVal\":\"10233\"}?
This is for a web service call with POST data with following content.And the web service gives me Bad request error when excluding this \ .hence the requirement
Please note i am using AFNetworking for the purpose of network data fetch
That looks like "nested JSON". You have to create JSON data for the array
arr first, and put that into the outer dictionary. Then create JSON data for the complete
object:
NSDictionary *sampledict = #{#"TextVal": #"10233"};
NSArray *arr = [NSArray arrayWithObject:sampledict];
NSData *innerJson = [NSJSONSerialization dataWithJSONObject:arr options:0 error:NULL];
NSString *innerJsonString = [[NSString alloc] initWithData:innerJson encoding:NSUTF8StringEncoding];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:innerJsonString forKey:#"sampleId"];
NSData *json = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(#"%#", jsonString);
Output:
{"sampleId":"[{\"TextVal\":\"10233\"}]"}

Resources