Add json file and print in console - ios

I know how to create a dummy json data and to print them in console like below code:
NSArray *jsonObject;
jsonObject = #[#{#"Id1":#"mad",
#"people1":#"300"},
#{#"Id2":#"normal",
#"people2":#"9",#"total2":#"300"}];
NSError *err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:nil];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error: &err];
NSLog(#"%#,%#",jsonArray);
I have one file name Areafiles.JSON. In that file I have some json data. I directly drag and drop in my project.
How can I read and print in my console like my above example?

For Swift:
Suppose you have a Json file titled a.json in your project that looks something like this:
{
"person":[
{
"name": "Bob",
"age": "16",
"employed": "No"
},
{
"name": "Vinny",
"age": "56",
"employed": "Yes"
}
]
}
Now just follow the three simple steps:
Read the file
Convert the contents of the file into an NSData
Convert the NSData into JSON object
Now you are free to use the Json object as you please:
// Get the path to the JSON File
if let path = NSBundle.mainBundle().pathForResource("a", ofType: "json")
{
// Load the contents of the file into an NSData object
if let jsonData = NSData(contentsOfFile: path)
{
do {
// Serialize the jsonData object to make a Json object
let jsonResult = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments)
if let persons : NSArray = jsonResult["person"] as? NSArray
{
// Print the contents of your file
print(persons)
}
} catch {
print("Problem converting jsonResult to dictionary")
}
}
}
Its the same process in both Swift and Objective-C.

Once you drag & drop a file in your project, the file goes in your application bundle. So you need to get the path of the file on the application bundle.
NSString* path = [[NSBundle mainBundle] pathForResource:#"Areafiles" ofType:#"json"];
Now you are ready to load its content on a string
NSString* content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
Then you want to obtain a dictionary from that string
NSArray *json = [NSJSONSerialization JSONObjectWithData:[content dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error:&error];

File -> NSData
// get path to the file
NSString *path = [[NSBundle mainBundle]pathForResource:#"Areafiles"
ofType:#"json"];
// NSData from the filepath
NSData *fileData = [NSData dataWithContentsOfFile:path];
NSData -> NSDictionary
NSError* error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:fileData
options:kNilOptions
error:&error];
if (error == nil) {
NSLog(#"%#", jsonDict);
return jsonDict;
}
else {
NSLog(#"Error reading JSON file");
return nil;
}

Related

How to convert Plist data to JSON format?

i am using plist to save my data locally when network connection is not available, and when network is available i want to sync my locally saved data to the web server.In this process i want to convert my plist data to JSON data and post that data to web server. Can any one help me one this?
You can access data from plist in dictionary format thenceforth serialize it to get json string.
NSString *path = [[NSBundle mainBundle] pathForResource:#"yourPlistName" ofType:#"plist"];
NSData* data = [NSData dataWithContentsOfFile:path];
NSDictionary* dict= [NSPropertyListSerialization propertyListFromData:data
mutabilityOption:NSPropertyListImmutable
format:NSPropertyListXMLFormat_v1_0
errorDescription:NULL];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
-----SWIFT 3-----
if let url = Bundle.main.url(forResource:"yourPlistName", withExtension: "plist") {
do {
let data = try Data(contentsOf:url)
let dict = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as! [String:Any]
let jsonData = try JSONSerialization.data(withJSONObject: dict , options: .prettyPrinted)
// jsondata your required data
} catch {
print(error)
}
}
You can do that with this code:
NSMutableDictionary *plistDic = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
Use the code below
NSString * plistPath = #“data.plist”;
NSMutableDictionary *plistData = [[NSMutableDictionary alloc] initWithContentsOfFile: plistPath];
NSError * err;
NSString * jsonStr = nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:plistData options:0 error:&err];
jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
My plist was an NSArray, not an NSDictionary, so I had to do this:
NSString *plistPath = [[NSBundle mainBundle] pathForResource:#"myPlist" ofType:#"plist"];
NSArray *menuArray = [[NSArray alloc] initWithContentsOfFile:plistPath];
NSError *err;
NSString *jsonStr = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:menuArray options:0 error:&err];
jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

Convert String to dictionary using NSJSON

How to convert string to dictionary.We are using NSJSON but getting nil value
NSString *decryptstr = [CTAES decrypt:text];
decryptstr contains below data
{
"status":"200","description":"OK","count":"4","reg_flag":1,"cars":
[],"appointments_count":"0","addbymecars":[{"gallery":
[],"imagescount":0,"id":"1924453","mypage_list_flag":0,"appointment_date":"",
"listing_status":"Active","sellername":"test ","sellernumber":"+918888888888","email":"ufhwifuw#gmail.com","make":"Hyundai","model":"i20","model_type":"Asta 1.4 CRDI","listing_type":"","listing_sorting_order":"","band_color":"","price":"65,59,595\/-","state":"Telangana","city":"Hyderabad","area":"","mfgyear":"2013","color":"Green","owner":"2","user_type":"person","dealer_id":"1503181","isfeatured":"0","fueltype":"Diesel","pincode":"0","mileage":"89,89,898","app_latitude":"","app_longitude":"","certification":"n","certification_text":"","images":{"ldpi":"http:\/\/imagecdn.cartrade.com\/notavailable80x60.jpg","mdpi":
"http:\/\/imagecdn.cartrade.com\/notavailable100x75.jpg","hdpi":"http:\/\/imagecdn.cartrade.com\/notavailable150x113.jpg","xhdpi":"http:\/\/imagecdn.cartrade.com\/notavailable200x150.jpg","xxhdpi":"http:\/\/imagecdn.cartrade.com\/notavailable300x225.jpg"},"usedcarshortlist":"0","postingdate":"04-Jan-2016","mobile_link":"http:\/\/testm.cartrade.com\/L1924453","transmission":
"Manual"},{"gallery":[],"imagescount":0,"id":"1924742","mypage_list_flag":0,"appointment_date":"","listing_status":"Active","sellername":"yuyu ","sellernumber":"+919898889989","email":"jhhgj#gmail.com","make":"Maruti Suzuki","model":"800","model_type":"AC","listing_type":"","listing_sorting_order":"","band_color":"","price":"15,64,654\/-","state":"Delhi","city":"New Delhi","area":"","mfgyear":"2014","color":"","owner":"1","user_type":"person","dealer_id":"1484907","isfeatured":"0","fueltype":"Petrol","pincode":"110001","mileage":"1,233","app_latitude":"28.6182","app_longitude":"77.2233",
"certification":"n","certification_text":"","images":{"ldpi":"http:\/\/imagecdn.cartrade.com\/notavailable80x60.jpg","mdpi":"http:\/\/imagecdn.cartrade.com\/notavailable100x75.jpg","hdpi":"http:\/\/imagecdn.cartrade.com\/notavailable150x113.jpg","xhdpi":"http:\/\/imagecdn.cartrade.com\/notavailable200x150.jpg","xxhdpi":"http:\/\/imagecdn.cartrade.com\/notavailable300x225.jpg"},"usedcarshortlist":"0","postingdate":"05-Feb-2016","mobile_link":"http:\/\/testm.cartrade.com\/L1924742","transmission":"Manual"},{"gallery":[],"imagescount":0,"id":"1924641","mypage_list_flag":0,"appointment_date":"","listing_status":"Active","sellername":"vcnvmcx ","sellernumber":"+919812345687","email":"chk#gmail.com","make":"Maruti Suzuki","model":"Alto 800","model_type":"LX","listing_type":"","listing_sorting_order":"",
"band_color":"","price":"2,50,000\/-","state":"Maharashtra","city":"Mumbai","area":"New Hyderabad","mfgyear":"2015","color":"","owner":"1","user_type":"person","dealer_id":"1503221","isfeatured":"0","fueltype":"Petrol","pincode":"500001","mileage":"50,000","app_latitude":"17.3897","app_longitude":"78.478","certification":"n","certification_text":"","images":{"ldpi":"http:\/\/imagecdn.cartrade.com\/notavailable80x60.jpg","mdpi":"http:\/\/imagecdn.cartrade.com\/notavailable100x75.jpg","hdpi":"http:\/\/imagecdn.cartrade.com\/notavailable150x113.jpg","xhdpi":"http:\/\/imagecdn.cartrade.com\/notavailable200x150.jpg","xxhdpi":"http:\/\/imagecdn.cartrade.com\/notavailable300x225.jpg"},
"usedcarshortlist":"1","postingdate":"03-Feb-2016","mobile_link":"http:\/\/testm.cartrade.com\/L1924641","transmission":"Manual"
}
]}
using NSJSON
NSError *error;
NSData *jsonData = [decryptstr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *returndict = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&error];
returndict getting nil value.
add this line before convert ur string
NSString *decryptstr = [CTAES decrypt:text];
decryptstr = [NSString stringWithFormat:#"%s",[decryptstr UTF8String]];
Your string doesn't contain any escape characters, which Objective-C cann't read directly. So add escape characters to your string using following snippet.
// *** Get your string data ***
NSString *decryptstr = [CTAES decrypt:text];
// *** Add Escape characters to your string ***
NSString *escaped = [decryptstr stringByReplacingOccurrencesOfString:#"\"" withString:#"\\\""];
NSError *error;
// *** Convert escaped string to Data ***
NSData *jsonData = [escaped dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *returndict = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&error];
NSLog(#"%#",returndict);
I just created one JSON file and copied your JSON data.
NSString *filePath = [[NSBundle mainBundle]pathForResource:#"data" ofType:#"json"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSError *err;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];

NSJSONSerialization Returns Error of NULL

I have the following code :
NSData * jsonData = [NSData dataWithContentsOfURL:location];
NSString* newStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *data = [newStr dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
if (jsonError) {
NSLog(#"JSON Error %#", [jsonError localizedDescription]);
}
NSArray * jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
Which is parsing the following JSON String :
{"author":"Oli Riman","content":"The museum shows us a view of pre-WWI society that includes doubts, fears, political protests etc. through newspaper cartoons of the time. Really interesting for adults who enjoy history. I wouldn't suggest this for kids who haven't studied WWI history or who don't read easily.","rating":"5","placeId":"40","date":"29-June-2015","reviewId":"9905A52D-76B2-4D42-8CA8-9158225C0D07"}
However I am getting a strange error code of :
domain: (null) - code: 0
Can anyone advise on what is causing this ?
Just tested the code on my simulator. Its working. You need to check if you are getting data from server or not.
If you want to test the parsing thing, you can do one thing-
Just store the data in json file and save it in the app bundle lets say file is "data.json"
and call below method, you will get data for sure.
- (void)readJsonData {
NSString *path = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"json"];
NSURL *url = [NSURL fileURLWithPath:path];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData: data
options: NSJSONReadingAllowFragments
error: &error];
NSLog(#"Parsed json data- %#", dict);
}

How to Parse an Array of Strings (JSON) - iOS?

I have JSON that reads like this:
{
"categories":["Love", "Hope, "Dreams"],
}
I am familiar with parsing arrays or dictionaries with objects, but I am slightly confused as to how to parse an array full of strings. How do I go about doing so?
use the following custom method
-(NSArray *)stringArrayFromJsonFile:(NSString *)jsonFileName withKey:(NSString *)key
{
NSData *fileContents = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:jsonFileName ofType:#"json"]];
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:fileContents options:kNilOptions error:&error];
NSArray * stringArray = [dict objectForKey:key];
return stringArray;
}
now call that method like
NSArray* stringArray = [self stringArrayFromJsonFile:#"yourJsonFileName" withKey:#"categories"];
You should get the data first.
NSString * JSONString = #"{\"somekey\":[\"somevalue\"]}";
NSData * JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
id JSONResult = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingAllowFragments error:nil];
if ([JSONResult isKindOfClass:[NSDictionary class]]) {
NSDictionary * dictionary = JSONResult;
} else {
...
}

arrayWithContentsOfFile and arrayWithContentsOfURL nil

When I call [NSArray arrayWithContentsOfFile:], I get nil.
NSURL *fileURL = [NSURL URLWithString:className relativeToURL:[self JSONDataRecordsDirectory]];
return [NSArray arrayWithContentsOfFile:[NSString stringWithFormat:#"%#", [fileURL path]]];
Alternatively, I also get nil when I call:
[NSArray arrayWithContentsOfURL:]
The results of all my files are in JSON here:
https://gist.github.com/neverbendeasy/03d047a6789b0ae14e1f
When I check the fileURLs, the data is there.
What am I missing?
You can't load a JSON file using NSArray arrayWith.... That method can only load a plist file with an array as the root.
If your file is a JSON file you should use:
NSData *jsonData = [NSData dataWithContentsOfURL:fileURL];
NSError *error = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if (jsonArray) {
// do something with jsonArray
} else {
NSLog(#"Couldn't load JSON from %#: %#", fileURL, error);
}
This assumes the top level of the JSON file is an array.
Use NSURL's
+ (id)fileURLWithPath:(NSString *)path
or
+ (id)fileURLWithPath:(NSString *)path isDirectory:(BOOL)isDir
instead of
+ (id)URLWithString:(NSString *)URLString
when working with the local filesystem.

Resources