ios - 如何在类属性中的 Objective C 中创建类似 json 的结构?

标签 ios objective-c json

我有这样的 View Controller 类

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

最佳答案

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

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

关于ios - 如何在类属性中的 Objective C 中创建类似 json 的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40866818/

相关文章:

objective-c - 如何在基于页面 View 的应用程序中加载 pdf 文件

ios - AFNetworking:重用方法

java - Spring 4中如何使用fasterxml Jackson JSON序列化

ios - 如何处理 UILabel 中泰文的高度?

ios - 使在 extern "C" block 中定义的类能够引用外部方法

ios - Codemagic iOS Flutter 部署在存档时失败

c++ - Objective-C++调整大小实例 vector 不起作用

objective-c - 向 NSMutableDictionary 添加条目

javascript - JavaScript 中无法解释的错误

javascript - 执行 `typeof JSON` 比较