Sundar
Sundar

Reputation: 4650

How to create json like structure in Objective C in class property?

I am having the view controller class like this

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (nonatomic, strong) NSDictionary *dictionary;

@end

ViewController.m

#import "ViewController.h"
#import "GoogleMaps.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    //HOW TO ACCESS THE PROPERTY VALUE HERE
    self.dictionary = @{};


    / DUMP ALL FOUND ITEMS
    for(DummyContainer* geoItem in geoItems) {
        NSDictionary *item = @{ 
            @"latitude":geoItem.latitude,
            @"longtitude":geoItem.longtitude
        };

        self.dictionary[geoItem.geoPoint.name] = item;
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

The expected format is

var container = {
    'location':{
        'latitude':1233,
        'longtitude':124
    }
}

This can be accessible via

let obj = container['location'];

for latitude access like this obj.latitude;

I am new to iOS please help me thanks in advance.

Upvotes: 0

Views: 160

Answers (1)

Syed Qamar Abbas
Syed Qamar Abbas

Reputation: 3677

For creating non extendable/immutable Dictionary Object

@property (strong, nonatomic) NSDictionary *myClassDictionary;    

For creating extendable/mutable Dictionary Object

@property (strong, nonatomic) NSMutableDictionary *myClassMutableDictionary;

Insert all of your values inside a Dictionary like this You exampleData

'location':{
        'latitude':1233,
        'longtitude':124
    }

NSDictionary *dict = @{@"lattitude":@"1233" , @"longitude":@"124"};
self.myClassDictionary = @{@"location":dict};//Convert this dictionary into JSON.

NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: self.myClassDictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString jsonString;
if (! jsonData) {
    NSLog(@"Got an error: %@", error);
} else {
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

Upvotes: 1

Related Questions