反射--> 解析JSON數據

来源:https://www.cnblogs.com/EchoHG/archive/2018/02/22/8458337.html
-Advertisement-
Play Games

方法一 Persons.json文件 Model.h類 Model.m類 調用 列印結果: 方法二 數據模型的父類是:JSONModel JSONModel的子類是:JSONPerson, JSONStudent, JSONTeacther等; JSONStudent.h中 註意:這是用OC來寫的! ...


 

方法一

Persons.json文件

[
 {
 "name": "Chris",
 "age": 18,
 "city": "Shanghai",
 "job": "iOS"
 },
 {
 "name": "Ada",
 "age": 16,
 "city": "Beijing",
 "job": "student"
 },
 {
 "name": "Rita",
 "age": 17,
 "city": "Xiamen",
 "job": "HR"
 }
 ]

 Model.h類

 1 #import <Foundation/Foundation.h>
 2 
 3 @interface PersonModel : NSObject
 4 
 5 @property (nonatomic, copy) NSString *name;
 6 @property (nonatomic, assign) NSInteger age;
 7 @property (nonatomic, copy) NSString *city;
 8 @property (nonatomic, copy) NSString *job;
 9 @property (nonatomic, copy) NSString *sex;
10 
11 - (instancetype)initWithNSDictionary:(NSDictionary *)dict;
12 
13 @end

 

Model.m類

 1 #import "PersonModel.h"
 2 #import <objc/runtime.h>
 3 
 4 @implementation PersonModel
 5 
 6 - (instancetype)initWithNSDictionary:(NSDictionary *)dict {
 7     self = [super init];
 8     if (self) {
 9         [self prepareModel:dict];
10     }
11     return self;
12 }
13 
14 - (void)prepareModel:(NSDictionary *)dict {
15     NSMutableArray *keys = [[NSMutableArray alloc] init];
16     
17     u_int count = 0;
18     objc_property_t *properties = class_copyPropertyList([self class], &count);
19     for (int i = 0; i < count; i++) {
20         objc_property_t property = properties[i];
21         const char *propertyCString = property_getName(property);
22         NSString *propertyName = [NSString stringWithCString:propertyCString encoding:NSUTF8StringEncoding];
23         [keys addObject:propertyName];
24     }
25     free(properties);
26     
27     for (NSString *key in keys) {
28         if ([dict valueForKey:key]) {
29             [self setValue:[dict valueForKey:key] forKey:key];
30         }
31     }
32 }
33 
34 @end

 

 

調用

1 NSString *file = [[NSBundle mainBundle] pathForResource:@"Persons" ofType:@"json"];
2     NSData *data = [NSData dataWithContentsOfFile:file];
3     NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
4     
5     for (NSDictionary *model in array) {
6         PersonModel *person = [[PersonModel alloc] initWithNSDictionary:model];
7         NSLog(@"%@, %ld, %@, %@", person.name, (long)person.age, person.city, person.job);
8     }

 

 

列印結果:

 

 


 

 

方法二

數據模型的父類是:JSONModel

JSONModel的子類是:JSONPerson, JSONStudent, JSONTeacther等;

JSONStudent.h中

 1 @import JSONModel;
 2 
 3 @interface JSONStudent : JSONModel
 4 
 5 @property (nonatomic, copy) NSString * id;
 6 @property (nonatomic, copy) NSString * name;
 7 @property (nonatomic, copy) NSString * nickName;
 8 @property (nonatomic, copy) NSString * phoneNumber;
 9 
10 @end

 

 

註意:這是用OC來寫的!

 

獲取屬性 

 1 func getAllProperties<T: JSONModel>(anyClass: T) -> [String] {
 2         var properties = [String]()
 3         let count = UnsafeMutablePointer<UInt32>.allocate(capacity: 0)
 4         let buff = class_copyPropertyList(object_getClass(anyClass), count)
 5         let countInt = Int(count[0])
 6         
 7         for i in 0..<countInt {
 8             let temp = buff![i]
 9             let tempPro = property_getName(temp)
10             let proper = String(utf8String: tempPro!)
11             properties.append(proper!)
12         }
13         return properties
14         
15     }

 

註意:獲取屬性使用Swift寫的,單純用Swift和OC要簡單!

使用

1 func returnListStudent(students: [JSONStudent]) {
2         for item in students {
3             let studentProperties = self.getAllProperties(anyClass: item)
4             for i in 0..< studentProperties.count{
5                 print("值是:\(item.value(forKey: studentProperties[I]))" + "屬性是:\(studentProperties[i])"self.dataError)
6             }
7         }
8     }

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 基於elasticsearch2.3.3寫的入門demo,含有創建index,刪除index,錄入數據,查詢、以及分頁,並且使用流行的ik分詞器。測試方式:使用 JNUIT TEST 來運行。 ...
  • 一,代碼優化: 代碼優化是任何優化技術的第一步,因為歸根結底網頁上的一切都是構建在代碼之上的。優秀的代碼可以節省寬頻,減少渲染延遲,以及提高頁面的可讀性和長遠的可維護性。下麵列出了一些在Web應用中編寫任何代碼時都應該記住的最佳實踐。 1,使用遵循Web標準的代碼。 2,精簡代碼。 3,減少HTTP ...
  • @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getW ...
  • 在Android Studio項目裡面有個local.properties文件,這個文件可以放一些系統配置。比如:sdk路徑、ndk路徑。 當然我們也可以在local.properties放一些自定義的配置,比如簽名文件: build.gradle 如何讀取local.properties欄位信息 ...
  • Objective-C allows you to define protocols, which declare the methods expected to be used for a particular situation. Protocols are implemented in the ...
  • NSLog method In order to print logs, we use the NSLog method in Objective-C programming language which we have used right from the Hello World example ...
  • AFNetworking是一個用於iOS、macOS、watchOS和tvOS的功能強大的網路庫。它構建在基礎URL載入系統之上,擴展了強大的高級網路抽象,並將其構建為Cocoa。它有一個模塊化的架構,設計良好,具有強大功能的api 使用 CocoaPods 引入 創建一個下載任務 創建一個上傳任務 ...
  • 鎖的用法在iOS中有幾種方法來解決多線程訪問同一個記憶體地址的互斥同步問題: 方法一,@synchronized(id anObject),(最簡單的方法)會自動對參數對象加鎖,保證臨界區內的代碼線程安全 方法二,NSLockNSLock對象實現了NSLocking protocol,包含幾個方法:l ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...