i am Newbie in iOS Development. I want to Parse an JSON Data From My WebServices for that I have written folliwing code
- (void)viewDidLoad
{
NSURL * url=[NSURL URLWithString:[NSString stringWithFormat:#"http://www.janvajevu.com/webservice/latest_post.php?page=%d",pageNum]];
dispatch_async(kBgQueue, ^{
data = [NSData dataWithContentsOfURL: url];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
-(void)fetchedData:(NSData *)responsedata
{
if (responsedata.length > 0)
{
NSError* error;
self.json= [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
if ([[_json objectForKey:#"data"] isKindOfClass:[NSArray class]])
{
NSArray *arr = (NSArray *)[_json objectForKey:#"data"];
[self.navuArray addObjectsFromArray:arr];
[self.navuTable reloadData];
NSLog(#"JSON Data %#",self.navuArray);
}
self.navuTable.hidden=FALSE;
}
Here Self.json is A JSON Dictionary and self.navuArray is my NSMutableArray when i print my Array then It returns Num. Please Give me Solution for it.
Its your navuArray that is not initialized before you are adding objects to it from array. Initialize it before you call for your data and then add objects to it.
Try this code
id jsonObject = [NSJSONSerialization JSONObjectWithData:webData options:kNilOptions error:&error];
table = [[UITableView alloc]init];
[dict objectForKey:#"data"];
NSArray *array = (NSArray *)jsonObject;
if ([[dict objectForKey:#"data"] isKindOfClass:[NSArray class]])
{
for(int i=0;i<[array count];i++)
{
dict1 = [array objectAtIndex:i];
[postIdArr addObject:[dict objectForKey:#"post_id]];
[postTitleArr addObject:[dict objectForKey:#"post_title"]];
[postTitleSlungArr addObject:[dict objectForKey:#"post_title_slug"]];
NSString *dateId = [dict objectForKey:#"post_date"];
NSArray *dateArray = [dateId componentsSeparatedByString:#" "];
[dateArrs addObject:[dateArray objectAtIndex:0]];
[timeArrs addObject:[dateArray objectAtIndex:1]];
//[dateIdArr addObject:[dict objectForKey:#"date"]];
[postViewsArr addObject:[dict objectForKey:#"post_views"]];
[imageArr addObject:[dict objectForKey:#"feature_image"]];
[shortArr addObject:[dict objectForKey:#"short_description"]];
[nameArr addObject:[dict objectForKey:#"author_name"]];
}
Related
I have dictionary data like this and one array on image.
{ "result":"Successful","data":{"id":"12","product_name":"12\" Round
Plate","sku":"ECOW12RP","description":"Diameter 12 inch x\tDepth 0.9
inch","price":"153.00","business_price":"365.00","image":[{"image":"1454499068ecow12rp_01.jpg"}],"pack_size":"20","business_pack_size":"50","category":"2,3","tax_class":"1","created":"2016-02-03","altered":"2016-02-03
17:52:58","status":"1","deleted":"0","arrange":"1","delivery":"150.00"}}
I want to parse all the key values from it. this is the code which i use for this task.
-(void)viewDidLoad
{
NSLog(#"d %ld", (long)id);
NSString* myNewString = [NSString stringWithFormat:#"%i", id];
NSURL *producturl = [NSURL URLWithString:#"http://dev1.brainpulse.org/ecoware1/webservices/product/" ];
NSURL *url = [NSURL URLWithString:myNewString relativeToURL:producturl];
NSData * imageData = [NSData dataWithContentsOfURL:url];
UIImage * productimage = [UIImage imageWithData:imageData];
NSURL *absURL = [url absoluteURL];
NSLog(#"absURL = %#", absURL);
NSURLRequest *request= [NSURLRequest requestWithURL:absURL];
[NSURLConnection connectionWithRequest:request delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response
{
data = [[NSMutableData alloc] init];
NSLog(#"Did receive response");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)thedata
{
[data appendData:thedata];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSDictionary *dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:#"data"];
NSLog(#"arr %#", dictionary);
[productdetail removeAllObjects];
for (NSString *tmp in dictionary)
NSMutableDictionary *temp = [NSMutableDictionary new];
[temp setObject:#"product_name" forKey:#"product_name"];
//[temp setObject:[tmp objectForKey:#"id"] forKey:#"id"];
// [temp setObject:[tmp objectForKey:#"image"] forKey:#"image"];
[productdetail addObject:temp];
NSLog(#"detail %#", productdetail);
}
I tried to parse string from nsdictionary with the help of for loop, but I get product details array null, i don't know why it not get key value.
i am parse data which is in nsdictionary but i have null array when i try to parse image array in this json data please look at this json data.
{"result":"Successful","data":{"id":"2","product_name":"6\" Round Plate","sku":"ECOW6RP","description":"Diameter 6.0 (inch) x Depth 0.6 (inch)\r\n\r\nPerfect for finger foods!","price":"42.89","business_price":"100.00","image":[{"image":"1454499251ecow6rp_01.jpg"}],"pack_size":"20","business_pack_size":"50","category":"2,3","tax_class":"1","created":"2016-01-19","altered":"2016-02-06 16:06:10","status":"1","deleted":"0","arrange":"1","delivery":"150.00"}}
try this
Option-1
NSDictionary *dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:#"data"];
[productdetail removeAllObjects];
if (dictionary)
{
NSMutableDictionary *temp = [NSMutableDictionary new];
[temp setObject:[dictionary objectForKey:#"product_name"] forKey:#"product_name"];
[productdetail addObject:temp];
}
Regarding your specific question to get the product_name data into your dictionary, this will work
NSDictionary *dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:#"data"];
NSMutableDictionary *temp = [NSMutableDictionary new];
if ([dictionary objectForKey:#"product_name"]){
[temp setObject:[dictionary objectForKey:#"product_name"] forKey:#"product_name"];
}
If you print out the dictionary you made, you should see it is in there.
NSLog(#"the temp dictionary value for ProductName: %#", [temp objectForKey:#"product_name"];
This question already has answers here:
How To Add New Keys and Values Into Plist Using Objective C?
(1 answer)
Save NSDictionary to plist
(3 answers)
Closed 7 years ago.
I have created JSON data store Into Plist. Now the problem is after JSON data storage, I need to add two set of keys into every array of dictionary items like below Image_2.The key name isParent - Boolean YES and isChild - Boolean YES with levels like mentioned below Image_2.
Now I have below structure of plsit datas Its perfectly working by below code.
I need to add two keys for outside of object subjectcount and inside of objectsubjectcount red marked datas.
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:&error];
NSDictionary *response = JSON[#"response"];
NSArray *keys = [response allKeys];
NSMutableArray *objects = [NSMutableArray new];
for (NSString *key in keys) {
NSMutableDictionary *object = response[key];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"subject = %#",object[#"subject"]];
NSArray *objectsWithSameSubject = [objects filteredArrayUsingPredicate:predicate];
NSInteger subjects = [object[#"subject"] integerValue];
if (subjects > 0) {
NSMutableArray *Objects_Subjectcount = [NSMutableArray new];
[object setObject:Objects_Subjectcount forKey:#"Objects_Subjectcount"];
for (NSInteger i = 0; i < subjects; i++) {
[Objects_Subjectcount addObject:object];// object or anything you need
}
}
[objects addObject:object];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = paths.firstObject;
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"File.plist"];
NSError *writeError = nil;
NSDictionary *finalDict = #{#"Objects": objects};
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:finalDict format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListImmutable error:&writeError];
if(plistData){
[plistData writeToFile:plistPath atomically:YES];
}
else {
NSLog(#"Error in saveData: %#", error);
}
NOTE : all the datas store by JSON but after storage need to add additional values by manually! Thats I am trying
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:finalDict format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListMutable error:&writeError];
Retrieve data from plist like this.
NSMutableDictionary *plistDic = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
Now suppose you want to update first array of dictionary then
NSMutableArray *array = [[NSMutableArray alloc]init:[plistDic objectAtIndex:0]]
You can do for loop if you want to change all array data...Right i am just using first object data..
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init:[array objectAtIncex:0]];
[dict addObject:"yourdata" forKey:"yourkey"];
[array replaceObject:dict atIndex:0];
[plistDic replaceObjectAtIndex:0 withObject:array];
And last
[plistDic writeToFile:plistPath atomically:YES];
The object from response[key] is immutable so it can't be modified as below:
[object setObject:Objects_Subjectcount forKey:#"Objects_Subjectcount"];
Making it mutable as below, it can be modified by any method add/remove/set.
NSMutableDictionary *object = [response[key] mutableCopy];
Hope using below modified block, you would see required changes.
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:&error];
NSDictionary *response = JSON[#"response"];
NSArray *keys = [response allKeys];
NSMutableArray *objects = [NSMutableArray new];
for (NSString *key in keys) {
NSMutableDictionary *object = [response[key] mutableCopy];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"subject = %#",object[#"subject"]];
NSArray *objectsWithSameSubject = [objects filteredArrayUsingPredicate:predicate];
NSInteger subjects = [object[#"subject"] integerValue];
if (subjects > 0) {
[object setObject:#"" forKey:#"level"];
[object setObject:#(YES) forKey:#"isParent"];
NSMutableArray *Objects_Subjectcount = [NSMutableArray new];
for (NSInteger i = 0; i < subjects; i++) {
[Objects_Subjectcount addObject:#{#"level":#(0), #"isChild":#(YES)}];
}
[object setObject:Objects_Subjectcount forKey:#"Objects_Subjectcount"];
}
[objects addObject:object];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = paths.firstObject;
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"File.plist"];
NSError *writeError = nil;
NSDictionary *finalDict = #{#"Objects": objects};
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:finalDict format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListImmutable error:&writeError];
if(plistData){
[plistData writeToFile:plistPath atomically:YES];
}
else {
NSLog(#"Error in saveData: %#", error);
}
I am receiving an arabic data through web service. I get data as a JSON object, but when I pass the value to an NSDictionary it shows nil and am not able to get key/pair value.i receive value till data,but i cant pass that to NSDictionary.
Here is the code:
(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
for (NSString *key in [json allKeys])
{
NSArray *feed = [json objectForKey:key];
for(int i=0; i<feed.count;i++)
{
for (NSString *key1 in [[feed objectAtIndex:i] allKeys])
{
if([key1 isEqualToString:#"newsTitle"])
{
NSString *value = [[feed objectAtIndex:i] objectForKey:key1];
[NewsTitleArray addObject:value];
}
else if([key1 isEqualToString:#"newsDescription"])
{
NSString *value = [[feed objectAtIndex:i] objectForKey:key1];
[NewsDescriptionArray addObject:value];
}}}}
You need to use proper encoding for your data, normally arabic content require ISO-Latin encoding. Though your code is wrong, you need to use correct NSURLConnection Delegate function to get complete data, you are trying to parse the incomplete data
See the changes below
Declare a variable
NSMutableData *receivedData;
Handle the delegate calls
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
//This delegate function gets called multiple times while fetching the data..
if(!receivedData){
receivedData=[[NSMutableData alloc] initWithData:data];
}else{
[receivedData appendData:data];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
//When the connection completes the processing, do you parsing
if(receivedData.length>0){
NSString *string = [[NSString alloc] initWithData:receivedData encoding:NSISOLatin1StringEncoding];
NSData *utf8Data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:utf8Data options:kNilOptions error:nil];
for (NSString *key in [json allKeys])
{
NSArray *feed = [json objectForKey:key];
for(int i=0; i<feed.count;i++)
{
for (NSString *key1 in [[feed objectAtIndex:i] allKeys])
{
if([key1 isEqualToString:#"newsTitle"])
{
NSString *value = [[feed objectAtIndex:i] objectForKey:key1];
[NewsTitleArray addObject:value];
}
else if([key1 isEqualToString:#"newsDescription"])
{
NSString *value = [[feed objectAtIndex:i] objectForKey:key1];
[NewsDescriptionArray addObject:value];
}
}
}
}
}
Note: The code above is not tested, might not work at first go, but it should be this way.
I hope it helps.
Cheers.
Good morning,
I'm trying to develop my first App and I'm using TableView in order to show my entries from a MySQL database and I'm having some trouble when I have to parse the JSON output.
I have already created the connection with my JSON, but now I need to save all the id in a single Array, all the user in another array, etc, etc. As you can see below in my second code, I need to store them in a NSArray. How can I do that?
That's my JSON
[{"id":"15","user":"1","imagen":"http:\/\/farmaventas.es\/images\/farmaventaslogo.png","date":"2014-09-13"}
,{"id":"16","user":"2","imagen":"http:\/\/revistavpc.es\/images\/vpclogo.png","date":"2014-11-11"}]
And that's my TableViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
NSString * urlString = [NSString stringWithFormat:#"http://website.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// Here I have to store my "user"
self.carMakes = [[NSArray alloc] initWithObjects: nil];
// Here I have to store my "imagen"
self.carModels = [[NSArray alloc] initWithObjects: nil];
}
Thanks in advance.
That's another solution with KVC
NSArray *carMakes = [json valueForKeyPath:#"#unionOfObjects.id"];
NSArray *carModels = [json valueForKeyPath:#"#unionOfObjects.user"];
First of all, you would want to fetch JSON on another thread, so you dont block your main thread with it:
#interface ViewController ()
#end
#implementation ViewController
-(void)viewDidLoad
{
[super viewDidLoad];
[self fetchJson];
}
-(void)fetchJson {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * urlString = [NSString stringWithFormat:#"http://website.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// I advice that you make your carModels mutable array and initialise it here,before start working with json
self.carModels = [[NSMutableArray alloc] init];
#try {
NSError *error;
NSMutableArray* json = [NSJSONSerialization
JSONObjectWithData:theData
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
if (error){
NSLog(#"%#",[error localizedDescription]);
}
else{
for(int i=0;i<json.count;i++){
NSDictionary * jsonObject = [json objectAtIndex:i];
NSString* imagen = [jsonObject objectForKey:#"imagen"];
[carModel addObject:imagen];
}
dispatch_async(dispatch_get_main_queue(), ^{
// If you want to do anything after you're done loading json, do it here
}
});
}
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// Here you have to store my "user"
self.userArray = [[NSMutableArray alloc]init];
for (NSDictionary *userInfo in json){
//get "user" from json
NSString* user = [userInfo objectForKey:#"user"];
//add to array
[userArray addObject:user];
}
You have use NSMutableArray to add object instead.
Since "json" is array of NSDictionary you can get iterate over it and add to arrays like this:
NSArray *json = #[#{#"id":#"15",#"user":#"1",#"imagen":#"http:\/\/farmaventas.es\/images\/farmaventaslogo.png",#"date":#"2014-09-13"},
#{#"id":#"16",#"user":#"2",#"imagen":#"http:\/\/revistavpc.es\/images\/vpclogo.png",#"date":#"2014-11-11"}];
NSArray *carMakes = [NSArray array];
NSArray *carModels = [NSArray array];
for (NSDictionary *dict in json) {
carMakes = [carMakes arrayByAddingObject:dict[#"id"]];
carModels = [carModels arrayByAddingObject:dict[#"user"]];
}
NSLog(#"%#",carMakes);
NSLog(#"%#",carModels);
Hello friends
Google-map-SDK
I am new to ios and working on the GOOGLE-MAP-SDK. and everything is going very well,but i am not able to use the annotations in this case due to which i am not able to locate my positions which i fetched from the placeAPI of the google.
So kindly help me out with my errors.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Code File
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-(IBAction)search:(id)sender
{
NSString *url = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=30.7343000,76.7933000&radius=500&types=food&name&sensor=true&key=AIzaSyCGeIN7gCxU8baq3e5eL0DU3_JHeWyKzic"];
//Formulate the string as URL object.
NSURL *googleRequestURL=[NSURL URLWithString:url];
// Retrieve the results of the URL.
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
//The results from Google will be an array obtained from the NSDictionary object with the key "results".
NSArray* places = [json objectForKey:#"results"];
//Write out the data to the console.
NSLog(#"Google Data: %#", places);
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here is the code from which i will recive the data and want to display it on the googlemap.
NSLog(#"Google Data: %#", places); is giving me the out put...
...
NSArray *markerForplaces = [NSMutableArray arrayWithCapacity:[responseResults count]];
for (NSDictionary *dict in responseResults) {
GMSMarker *markerForplace = [self markerForGooglePlaceFromDictionary:dict error:nil];
if (markerForplace) {
[markerForplaces addObject:markerForplace];
markerForplace.map = self.mapView;
}
}
...
- (GMSMarker*)markerForGooglePlaceFromDictionary:(NSDictionary*)dict {
CLLocationCoordinate2D coordinate = [self coordinateForPlace:dict];
GMSMarker *marker = [GMSMarker markerWithPosition:coordinate];
marker.userInfo = dict; //save place
}
- (CLLocationCoordinate2D)coordinateForPlace:(NSDictionary*)dictionary {
NSDictionary *geo = [dictionary objectForKey:#"geometry"];
if ([geo isKindOfClass:[NSDictionary class]]) {
NSDictionary *loc = [geo objectForKey:#"location"];
if ([loc isKindOfClass:[NSDictionary class]]) {
NSString *lat = [loc objectForKey:#"lat"];
NSString *lng = [loc objectForKey:#"lng"];
return CLLocationCoordinate2DMake([lat doubleValue], [lng doubleValue]);
}
}
return CLLocationCoordinate2DMake(0, 0);
}