【问题标题】:How to create json like structure in Objective C in class property?如何在类属性的Objective C中创建类似json的结构?
【发布时间】:2016-11-29 13:13:42
【问题描述】:

我有这样的视图控制器类

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 新手,请帮助我提前谢谢。

【问题讨论】:

标签: ios objective-c json


【解决方案1】:

用于创建不可扩展/不可变的字典对象

@property (strong, nonatomic) NSDictionary *myClassDictionary;    

用于创建可扩展/可变字典对象

@property (strong, nonatomic) NSMutableDictionary *myClassMutableDictionary;

像这样在字典中插入所有值 你的例子数据

'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];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多