json数据转化成模型对象

具体思想:

1.将模型对象的属性名和属性类型的创建规则  应与json数据的key-value一一对应。

2.在模型对象初始化之前,给模型对象的每一个属性名赋默认的值。比较 NSString类型默认赋值@"",NSNumber默认赋值

[NSNull null]

3.以json数据的key作为属性名,value作为值给模型数据一一赋值。

有三个重要的方法:

// 获取类的所有Property

1. objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)

// 获取一个Property的变量名

2. const char *property_getName(objc_property_t property)

// 获取一个Property的详细类型表达字符串

3. const char *property_getAttributes(objc_property_t property)

如下面方法可以读取模型(model)里的每一个属性,并且将属性名和类型转换成key-value的形式保存起来

static NSDictionary *primitivesNames = nil;
//获取一个类的属性名和类型
+(NSDictionary*)getClassPropertysAndType
{
    if(primitivesNames== nil){
        primitivesNames = @{@"f":@"float", @"i":@"int", @"d":@"double", @"l":@"long", @"c":@"BOOL", @"s":@"short", @"q":@"long",
                            //and some famos aliases of primitive types
                            // BOOL is now "B" on iOS __LP64 builds
                            @"I":@"NSInteger", @"Q":@"NSUInteger", @"B":@"BOOL",

                            @"@?":@"Block"};
    }
    NSMutableDictionary *properts_info = [[NSMutableDictionary alloc] init];

    Class curClass = [self class];
    NSScanner *scanner = nil;
    NSString* propertyType = nil;

    while (curClass && curClass != [NSObject class]) {

        objc_property_t  *propItems;
        unsigned int     ncount = 0;
//        获取类的所有Property
        propItems = class_copyPropertyList(curClass, &ncount);

        for(int i = 0; i < ncount; i++){
            objc_property_t prop_item = propItems[i];
            // 获取一个Property的变量名
            const char *properName = property_getName(prop_item);
            // 获取一个Property的详细类型表达字符串
            const char *attribute = property_getAttributes(prop_item);

            NSString* propertyAttributes = @(attribute);

            // NSLog(@"---------->property attributes:%@",propertyAttributes);

            NSString  *proper_Name = @(properName);

            NSArray* attributeItems = [propertyAttributes componentsSeparatedByString:@","];
            //ignore read-only properties
            if([attributeItems containsObject:@"R"]){
                continue;//to next property
            }

            //check for 64b BOOLs
            if ([propertyAttributes hasPrefix:@"Tc,"]) {
                //mask BOOLs as structs so they can have custom convertors
                propertyType = @"BOOL";
            }

            scanner = [NSScanner scannerWithString:propertyAttributes];
            [scanner scanUpToString:@"T" intoString: nil];
            [scanner scanString:@"T" intoString:nil];

            //check if the property is an instance of a class
            if ([scanner scanString:@"@\"" intoString: &propertyType]) {

                [scanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@"\"<"]
                                        intoString:&propertyType];

                //read through the property protocols
                while ([scanner scanString:@"<" intoString:NULL]) {

                    [scanner scanUpToString:@">" intoString:&propertyType];

                    [scanner scanString:@">" intoString:NULL];
                }
            }
            //check if the property is a structure
            else if ([scanner scanString:@"{" intoString: &propertyType]) {
                [scanner scanCharactersFromSet:[NSCharacterSet alphanumericCharacterSet]
                                    intoString:&propertyType];

            }
            else if([[attributeItems firstObject] isEqualToString:@"[email protected]"]){
                propertyType = @"id";
            }
            else if([[attributeItems firstObject] isEqualToString:@"[email protected]?"]){
                propertyType = @"Block";
            }
            //the property must be a primitive
            else {
                //the property contains a primitive data type
                [scanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@","]
                                        intoString:&propertyType];
                //get the full name of the primitive type
                propertyType = primitivesNames[propertyType];
            }

            if(propertyType){
                properts_info[proper_Name] = propertyType;
            }

        }
        free(propItems);

        curClass = [curClass superclass];
    }

    NSDictionary *prop_info = [properts_info copy];
    properts_info = nil;

    return prop_info;
}

具体实现过程,可在github中下载源代码。下载路径:https://github.com/wydxy/json-

时间: 2024-10-20 22:16:09

json数据转化成模型对象的相关文章

JSON数据转化成模型

JSON数据转化成模型 // 1.创建url NSURL *url = kSUNUrl(@"video"); // 2.创建request NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 3.发送请求数据 NSOperationQueue *queue = [NSOperationQueue mainQueue]; [NSURLConnection sendAsynchronousRequest:request

把json数据转化成对象

把json数据转化到一个对象中,再用对象直接调用 1 package com.lxj.register; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.net.MalformedURLException; 7 import java.net.URL; 8 9 import net.sf.json.JSONObjec

iOS中将后台JSON数据转化为模型的总结

1. 再拿到了Json数据后怎么把字典写到数组里面去呢? 方法1:用最原始的方法 -(instancetype)initWithDict:(NSDictionary *)dict { if(self = [super init]) { [self setValuesForKeysWithDictionary:dict]; } return self; } +(instancetype)modelWithDict:(NSDictionary *)dict { return [[self alloc

json数据转化成实体 存到数据库.

直接看步骤吧 1.一般我们会调用别人给的webservice获取一个字符串数据.如果为String data="xxxxxxxxxx";  这个data事实上就是样例EnterpriseInfoEntity 的多条记录 2.  把data转换为JSONArray JSONArray arr =new JSONArray(); arr = JSONArray.fromObject(data); 3.  我们是调用JSONObject 的toBean方法.讲这条数据相应到我们写的entit

SpringMVC中出现&quot; 400 Bad Request &quot;错误(用@ResponseBody处理ajax传过来的json数据转成bean)的解决方法

最近angularjs post到后台 400一头雾水 没有任何错误. 最后发现好文,感谢作者 SpringMVC中出现" 400 Bad Request "错误(用@ResponseBody处理ajax传过来的json数据转成bean)的解决方法 今天开发过程中,在SpringMVC中的Action中处理前台ajax请求传过来的json数据直接转成对应的实体类时出错:400 Bad Request,后台也不报错,400指的的是请求无效(请求有语法问题或者不能满足请求),调试了好长时间

IOS中将字典转成模型对象

作为IOS开发初级者今天学习了 如何将plist数据字典转成 数据对象数组中 .有点像C#中解析xml数据 的过程. apps.plist的xml数据是这样的 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList

JSON字符串转换成Map对象

页面向后台action传递一个json字符串,需要将json字符串转换成Map对象 import java.util.HashMap; import java.util.Iterator; import java.util.Map; import net.sf.json.JSONObject; public Map<String, String> toMap(Object object) { Map<String, String> data = new HashMap<Str

js中json字符串转成js对象

json字符串转成js对象我所知的方法有2种: //json字符串转换成json对象 var str_json = "{name:'liuchuan'}"; //json字符串 //1. 函数对象构造定义 var obj1 = new Function("return " + str_json)(); console.log(obj1.name); //2. eval函数 var obj2 = eval("(" + str_json + &quo

js将json数组转成tree对象

昨天遇到一道面试题,手写js将json数组转成tree对象,昨天写错了,今天特意想了下,思路其实挺简单,循环+递归,获取子节点对象. 1 let data = [ 2 {'parent_id': 0, 'id': 1, 'value': 'XXX'}, 3 {'parent_id': 1, 'id': 3, 'value': 'XXX'}, 4 {'parent_id': 4, 'id': 6, 'value': 'XXX'}, 5 {'parent_id': 3, 'id': 5, 'valu