方法一

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. pandas与sqlalchemy交互实现科学计算

      import pandas as pd import numpy as np from sqlalchemy import create_engine #建立数据库引擎 engine = crea ...

  2. linux基本介绍和使用

    基本介绍 Linux入门教程 快捷键     linux 快捷键 用户及用户组 linux之用户和用户组

  3. for in 循环

    for  in循环可以循环遍历数组  关键也可以循环遍历对象!而一般的for循环只能循环遍历数组, 当循环遍历对象时key值代表键值对的键,obj[key]则是对应键的值: 当循环遍历数组时,数组不是 ...

  4. Linux 命令locate

    原文:https://blog.csdn.net/liang19890820/article/details/53285624 简述 locate 可以很快速的搜寻档案系统内是否有指定的档案.其方法是 ...

  5. mvc,EntityFramework调用分页存储过程

    此文讲述mvc4+entityframework6+sqlserver2008环境下调用存储过程,实现分页. 1.分页存储过程代码如下: 分页原理用的row_number()和over()函数实现(没 ...

  6. commonjs模块和es6模块的区别?

    commonjs模块和es6模块最主要的区别:commonjs模块是拷贝,es6模块是引用,但理解这些,先得理解对象复制的问题,在回过头来理解这两模块的区别. 一.基本数据类型的模块 ./a1.js ...

  7. zabbix宏(macro)使用:自定义监控阈值

    一.简单应用场景 zabbix在监控cpu load时并没有考虑客户端cpu的个数和核心数量,当平均5分钟的负载达到5时zabbix执行报警动作,这样是非常不合理的,笔者的被监控机器有四核和单核,现在 ...

  8. zedboard上首个驱动实践——Led

    // led驱动 *myled.c*//头文件 #include<linux/module.h> //最基本的文件,支持动态添加和卸载模块 #include<linux/kernel ...

  9. windows版mysql5.7.18安装

    windows版mysql5.7.18安装 初始化命令:C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqld.exe --defaults-file=& ...

  10. Cartographer源码阅读(3):程序逻辑结构

    Cartographer早期的代码在进行3d制图的时候使用了UKF方法,查看现有的tag版本,可以转到0.1.0和0.2.0查看,包含kalman_filter文件夹. 文件夹中的pose_track ...