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];
Related
Im having hard time while trying to parse the following json array. How to parse it. The other answers in web doesn't seem to solve my problem.
{
"status": 1,
"value": {
"details": [
{
"shipment_ref_no": "32",
"point_of_contact": {
"empid": ""
},
"products": {
"0": " Pizza"
},"status": "2"
},
{
"shipment_ref_no": "VAPL/EXP/46/14-15",
"point_of_contact": {
"empid": "60162000009888"
},
"products": {
"0": "MAIZE/CORN STARCH"
},
"status": "5"
}
]
}
}
I have to access the values of each of those keys.
Following is my code
NSString* pendingResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [pendingResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSArray *argsArray = [[NSArray alloc] initWithArray:[jsonDic objectForKey:#"details"]];
NSDictionary *argsDict = [[NSDictionary alloc] initWithDictionary:[argsArray objectAtIndex:0]];
NSLog(#"keys = %#", jsonDic[#"values"]);
This is how you can parse your whole dictionary:
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray *details = [[dataDictionary objectForKey:#"value"] objectForKey:#"details"];
for (NSDictionary *dic in details) {
NSString *shipmentRefNo = dic[#"shipment_ref_no"];
NSDictionary *pointOfContact = dic[#"point_of_contact"];
NSString *empId = pointOfContact[#"empid"];
NSDictionary *products = dic[#"products"];
NSString *zero = products[#"0"];
NSString *status = dic[#"status"];
}
NSString *pendingResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [pendingResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSArray *argsArray = [[NSArray alloc] initWithArray:[jsonDic objectForKey:#"details"]];
//argsArray holds objects in form of NSDictionary.
for(NSDictionary *response in argsArray) {
//String object
NSLog(#"%#", [response valueForKey:#"shipment_ref_no"]);
//Dictionary object
NSLog(#"%#", [[response objectForKey:#"point_of_contact"] valueForKey:#"empid"]);
//String object
NSLog(#"%#", [response valueForKey:#"status"]);
//Dictionary object
NSLog(#"%#", [[response objectForKey:#"products"] valueForKey:#"0"]);
}
I believe you should surely ask your server developer to update the response format.
Also, you can always use Model classes to parse your data. Please check this, How to convert NSDictionary to custom object.
And yes, I'm using this site to check my json response.
EDIT: Following answer is in javascript!
You can parse your json data with:
var array = JSON.parse(data);
and then you can get everything like this:
var refno = array["value"]["details"][0]["shipment_ref_no"];
you can parse like ...
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSDictionary *dictValue = [[NSDictionary alloc] initWithDictionary:[jsonDic objectForKey:#"value"]];
NSArray *arrDetails = [[NSArray alloc] initWithArray:[dictValue objectForKey:#"details"]];
for (int i=0; i<arrDetails.count; i++)
{
NSDictionary *dictDetails=[arrDetails objectAtIndex:i];
NSDictionary *dictContact = [[NSDictionary alloc] initWithDictionary:[dictDetails objectForKey:#"point_of_contact"]];
NSDictionary *dictProduct = [[NSDictionary alloc] initWithDictionary:[dictDetails objectForKey:#"products"]];
}
NSDictionary *response = //Your json
NSArray *details = response[#"value"][#"details"]
etc. Pretty easy
Update your code as follows. You are trying to read the details array from the top level whereas in your data its inside the value key. So you should read the value dict and within that read the details array.
NSString* pendingResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [pendingResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSDictionary *valueDict = [jsonDic objectForKey:#"value"];
NSArray *argsArray = [[NSArray alloc] initWithArray:[valueDict objectForKey:#"details"]];
NSDictionary *argsDict = [[NSDictionary alloc] initWithDictionary:[argsArray objectAtIndex:0]];
NSLog(#"keys = %#", jsonDic[#"values"]);
I think your problem is that you have:
NSLog(#"keys = %#", jsonDic[#"values"]);
But it should be:
NSLog(#"keys = %#", jsonDic[#"value"]);
Below is code for parsing JSON array. i have used to parse JSON array from file but you can also do this using response link also.I have provided code for both and are below.
// using file
NSString *str = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"json"];
NSData *data = [[NSData alloc]initWithContentsOfFile:str];
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSMutableDictionary *dictValues = [[NSMutableDictionary alloc]initWithDictionary:[dict valueForKey:#"value"]];
NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[dictValues valueForKey:#"details"] copyItems:YES];
NSLog(#"Array Details :- %#",array);
// using url
NSURL *url = [NSURL URLWithString:#"www.xyz.com"]; // your url
NSData *data = [[NSData alloc]initWithContentsOfURL:url];
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSMutableDictionary *dictValues = [[NSMutableDictionary alloc]initWithDictionary:[dict valueForKey:#"value"]];
NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[dictValues valueForKey:#"details"] copyItems:YES];
NSLog(#"Array Details :- %#",array);
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;
}
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);
}
I want to convert Localizable.strings file to JSON:
"Key" = "Localized Str";
To
"Key" : "Localized Str",
Is there any ready solution? Or better write own script?
NSString *path = [[NSBundle mainBundle] pathForResource:#"Localizable"
ofType:#"strings"
inDirectory:nil
forLocalization:#"en"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted
error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
How to convert NSDictionary to NSString which contains JSON of NSDictionary ?
I have tried like but without success
//parameters is NSDictionary
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:0
error:&error];
if jsonData is NSDictionary
NSString *str=[NSString stringWithFormat:#"json data is %#", jsonData];
OR if jsonData is NSData
NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSASCIIStringEncoding];
If you just want to inspect it, you can create a NSString:
NSString *string = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
But if you're writing it to a file or sending it to a server, you can just use your NSData. The above construct is useful for examining the value for debugging purposes.