方法一

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类

 #import <Foundation/Foundation.h>

 @interface PersonModel : NSObject

 @property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy) NSString *city;
@property (nonatomic, copy) NSString *job;
@property (nonatomic, copy) NSString *sex; - (instancetype)initWithNSDictionary:(NSDictionary *)dict; @end

Model.m类

 #import "PersonModel.h"
#import <objc/runtime.h> @implementation PersonModel - (instancetype)initWithNSDictionary:(NSDictionary *)dict {
self = [super init];
if (self) {
[self prepareModel:dict];
}
return self;
} - (void)prepareModel:(NSDictionary *)dict {
NSMutableArray *keys = [[NSMutableArray alloc] init]; u_int count = ;
objc_property_t *properties = class_copyPropertyList([self class], &count);
for (int i = ; i < count; i++) {
objc_property_t property = properties[i];
const char *propertyCString = property_getName(property);
NSString *propertyName = [NSString stringWithCString:propertyCString encoding:NSUTF8StringEncoding];
[keys addObject:propertyName];
}
free(properties); for (NSString *key in keys) {
if ([dict valueForKey:key]) {
[self setValue:[dict valueForKey:key] forKey:key];
}
}
} @end

调用

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

打印结果:


方法二

数据模型的父类是:JSONModel

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

JSONStudent.h中

 @import JSONModel;

 @interface JSONStudent : JSONModel

 @property (nonatomic, copy) NSString * id;
@property (nonatomic, copy) NSString * name;
@property (nonatomic, copy) NSString * nickName;
@property (nonatomic, copy) NSString * phoneNumber; @end

注意:这是用OC来写的!

获取属性

 func getAllProperties<T: JSONModel>(anyClass: T) -> [String] {
var properties = [String]()
let count = UnsafeMutablePointer<UInt32>.allocate(capacity: )
let buff = class_copyPropertyList(object_getClass(anyClass), count)
let countInt = Int(count[]) for i in ..<countInt {
let temp = buff![i]
let tempPro = property_getName(temp)
let proper = String(utf8String: tempPro!)
properties.append(proper!)
}
return properties }

注意:获取属性使用Swift写的,单纯用Swift和OC要简单!

使用

 func returnListStudent(students: [JSONStudent]) {
for item in students {
let studentProperties = self.getAllProperties(anyClass: item)
for i in ..< studentProperties.count{
print("值是:\(item.value(forKey: studentProperties[I]))" + "属性是:\(studentProperties[i])"self.dataError)
}
}
}

方法三

User.swift

 import UIKit

 class User: NSObject {
var name:String = "" //姓名
var nickname:String? //昵称
var age:Int? //年龄
var emails:[String]? //邮件地址
}

Mirror

属性

//    实例化
let user = User()
let mirror: Mirror = Mirror(reflecting:user) // subjectType:对象类型 print(mirror.subjectType) // 打印出:User // children:反射对象的属性集合 // displayStyle:反射对象展示类型 // advance 的使用
let children = mirror.children
let p0 = advance(children.startIndex, , children.endIndex) // name 的位置
let p0Mirror = Mirror(reflecting: children[p0].value) // name 的反射
print(p0Mirror.subjectType) //Optional<String> 这个就是name 的类型

调用:

     @objc func testOne() {
// 得到应用名称
let nameSpace = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String
let clsName = "User"
// 使用NSClassFromString通过类名得到实例(得到类的完整路径, 注意分隔符是小数点;并判断数据类型是否符合预期。 备注: as?后面的格式是类名.Type, cls可能是nil)
guard let cls = NSClassFromString(nameSpace + "." + clsName) as? NSObject.Type else { return } //得到类完整路径
print("------_>\(cls)")
let user = cls.init()
print("------111111_>\(user)") // 使用Mirror得到属性值
let mirror = Mirror(reflecting: user)
for case let(key?, value) in mirror.children {
print("key:\(key), value: \(value)") //打印成员属性
}
print(mirror.subjectType) //反射对象的数据类型</span> }

打印:

反射--> 解析JSON数据的更多相关文章

  1. fastjson生成和解析json数据,序列化和反序列化数据

    本文讲解2点: 1. fastjson生成和解析json数据 (举例:4种常用类型:JavaBean,List<JavaBean>,List<String>,List<M ...

  2. Android网络之数据解析----使用Google Gson解析Json数据

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  3. fastjson生成和解析json数据

    本文讲解2点: 1. fastjson生成和解析json数据 (举例:4种常用类型:JavaBean,List<JavaBean>,List<String>,List<M ...

  4. TypeToken 是google提供的一个解析Json数据的类库中一个类

    Type listType = new TypeToken<LinkedList<User>>(){}.getType(); Type是java里的reflect包的Type ...

  5. Android解析Json数据之Gson解析

    Gson是谷歌官方提供的解析json数据的工具类.json数据的解析能够使用JSONObject和JSONArray配合使用解析数据,可是这样的原始的方法对于小数据的解析还是有作用的,可是陪到了复杂数 ...

  6. 使用Python解析JSON数据的基本方法

    这篇文章主要介绍了使用Python解析JSON数据的基本方法,是Python入门学习中的基础知识,需要的朋友可以参考下:     ----------------------------------- ...

  7. 使用jQuery解析JSON数据

    我们先以解析上例中的comments对象的JSON数据为例,然后再小结jQuery中解析JSON数据的方法. 上例中得到的JSON数据如下,是一个嵌套JSON: {"comments&quo ...

  8. [转]javascript eval函数解析json数据时为什加上圆括号eval("("+data+")")

    javascript eval函数解析json数据时为什么 加上圆括号?为什么要 eval这里要添加 “("("+data+")");//”呢?   原因在于: ...

  9. 用jquery解析JSON数据的方法以及字符串转换成json的3种方法

    用jquery解析JSON数据的方法,作为jquery异步请求的传输对象,jquery请求后返回的结果是 json对象,这里考虑的都是服务器返回JSON形式的字符串的形式,对于利用JSONObject ...

随机推荐

  1. jquery.ajax与axios及定义拦截器

    首先导入jquery和axios包 jquery.ajax function reg(){ var username = $("#username").val(); var pas ...

  2. byte数组存储到mysql

    public int AddVeinMessage(byte[] data)//插入数据库 { using (BCSSqlConnection = new MySqlConnection(strCon ...

  3. 使用Apache CXF根据wsdl文件生成代码

    1.去官网下载,我用的是apache-cxf-2.5.10.zip 2.解压 3.通过命令行进入Apache CXF的bin目录,如我的目录是D:\BIS\axis2\apache-cxf-2.7.1 ...

  4. jq优化

    1.使用链式写法 $('div').find('h3').eq(2).html('Hello');采用链式写法时,jQuery自动缓存每一步的结果,因此比非链式写法要快.根据测试,链式写法比(不使用缓 ...

  5. Erlang调度器

    1. Erlang 抢占式调度 Erlang实现公平调度基于Reduction Budget(运行次数限制).每一个进程创建时初始reduction budget值为2000,任何Erlang系统中的 ...

  6. SQL数据库中临时表、临时变量和WITH AS关键词创建“临时表”的区别

    原文链接:https://www.cnblogs.com/zhaowei303/articles/4204805.html SQL数据库中数据处理时,有时候需要建立临时表,将查询后的结果集放到临时表中 ...

  7. Mysql安装方法介绍

    MySQL的yum安装方法 centos7默认不再使用mysql而是用mariadb来代替mysql [root@yxh6 ~]# yum install mysql-server 已加载插件:fas ...

  8. 晨枫U盘启动盘制作工具V4.0-安装原版Win7

    第一类方法(32位64位系统通用): [1]找到Windows7系统的iso镜像,用UltraISO或者WinRAR打开iso镜像,然后提取/解压所有文件到你的U盘根目录. [2]在你的U盘里找到名为 ...

  9. OpenCV矩形检测

    OpenCV矩形检测 需求:提取图像中的矩形,图像存在污染现象,即矩形区域不是完全规则的矩形. 思路一:轮廓法 OpenCV里提取目标轮廓的函数是findContours,它的输入图像是一幅二值图像, ...

  10. Exception in thread “main” java.sql.SQLException: No suitable driver

    问题背景:通过Spark SQL的jdbc去读取Oracle数据做测试,在本地的idea中没有报任务错误.但是打包到集群的时候报: Exception in thread “main” java.sq ...