2016-11-29 96 views
0

我有這樣如何在類屬性中的Objective C中創建json結構?

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 

預期的格式的視圖控制器類是

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

這可以通過

let obj = container['location'];

可以訪問像這樣 obj.latitude;

  • 問題1緯度訪問:如何創建一個類屬性作爲字典和類內部訪問?
  • 問題2:如何創建JSON結構並訪問值?

我是新來的iOS請提前幫助我。

+0

http://www.appcoda.com/fetch-parse-json-ios-programming-教程/這可以幫助 – PrafulD

+0

你正在混合Objective-C和Swift。我建議只從Swift和Swift開始。 – shallowThought

+0

請幫我找出目標C代碼。我正在尋找目標c – Sundar

回答

1

爲了創建不可延伸/一成不變Dictionary對象

@property (strong, nonatomic) NSDictionary *myClassDictionary;  

爲了創建可擴展/可變Dictionary對象

@property (strong, nonatomic) NSMutableDictionary *myClassMutableDictionary; 

插入所有的值的字典裏是這樣 您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]; 
}