IOS dictionary and model convert each other

Source: Internet
Author: User

////HYBJSONModel.h//Json2modeldemo////Created by Huangyibiao on 14-9-15.//Copyright (c) 2014 Home. All rights reserved.//#import<Foundation/Foundation.h>/*! * @brief JSON into model, or convert model to JSON * @author Huangyibiao*/@interfaceHybjsonmodel:nsobject/*! * @brief Convert object (model) to Dictionary * @param model Object * @return return dictionary*/+ (Nsdictionary *) Dictionarywithmodel: (ID) model;/*! * @brief Get all property names for model * @param models Model Object * @return return all property values in the model*/+ (Nsarray *) Propertiesinmodel: (ID) model;/*! * @brief convert dictionary to model, model class named ClassName * @param dict Dictionary Object * @param className class name * @return return Data Model object*/+ (ID) Modelwithdict: (nsdictionary *) dict className: (NSString *) ClassName;@end
////HYBJSONMODEL.M//Json2modeldemo////Created by Huangyibiao on 14-9-15.//Copyright (c) 2014 Home. All rights reserved.//#import "HYBJSONModel.h"#import<objc/runtime.h>typedef ns_enum (Nsinteger, Hybjsonmodeldatatype) {Khybjsonmodeldatatypeobject=0, Khybjsonmodeldatatypebool=1, Khybjsonmodeldatatypeinteger=2, Khybjsonmodeldatatypefloat=3, Khybjsonmodeldatatypedouble=4, Khybjsonmodeldatatypelong=5,};@implementationHybjsonmodel/*! * @brief Convert object (model) to Dictionary * @param model Object * @return return dictionary*/+ (Nsdictionary *) Dictionarywithmodel: (ID) Model {if(model = =Nil) {        returnNil; } nsmutabledictionary*dict =[[Nsmutabledictionary alloc] init]; //Get class name/Get Class object by class nameNSString *classname = Nsstringfromclass ([modelclass]); IDClassobject =Objc_getclass ([ClassName utf8string]); //Get all PropertiesUnsignedintCount =0; objc_property_t*properties = Class_copypropertylist (Classobject, &count); //Traverse All Properties     for(inti =0; I < count; i++) {        //Get Propertiesobjc_property_t property =Properties[i]; //Get Property nameNSString *propertyname =[[NSString alloc] Initwithcstring:property_getname (property)        Encoding:nsutf8stringencoding]; //Get attribute value        IDPropertyValue =Nil; IDValueobject =[model Valueforkey:propertyname]; if([Valueobject Iskindofclass:[nsdictionaryclass]]) {PropertyValue=[Nsdictionary Dictionarywithdictionary:valueobject]; } Else if([Valueobject Iskindofclass:[nsarrayclass]]) {PropertyValue=[Nsarray Arraywitharray:valueobject]; } Else{propertyvalue= [NSString stringWithFormat:@"%@", [model Valueforkey:propertyname]];    } [Dict Setobject:propertyvalue forkey:propertyname]; }    return[dict copy];}/*! * @brief Get all property names for model * @param models Model Object * @return return all property values in the model*/+ (Nsarray *) Propertiesinmodel: (ID) Model {if(model = =Nil) {        returnNil; } Nsmutablearray*propertiesarray =[[Nsmutablearray alloc] init]; NSString*classname = Nsstringfromclass ([modelclass]); IDClassobject =Objc_getclass ([ClassName utf8string]); unsignedintCount =0; objc_property_t*properties = Class_copypropertylist (Classobject, &count);  for(inti =0; I < count; i++) {        //Get Property nameobjc_property_t property =Properties[i]; NSString*propertyname =[[NSString alloc] Initwithcstring:property_getname (property)        Encoding:nsutf8stringencoding];    [Propertiesarray Addobject:propertyname]; }        return[Propertiesarray copy];}/*! * @brief convert dictionary to model, model class named ClassName * @param dict Dictionary Object * @param className class name * @return return Data Model object*/+ (ID) Modelwithdict: (nsdictionary *) dict className: (NSString *) ClassName {if(dict = = Nil | | className = NIL | | classname.length = =0) {        returnNil; }        IDModel =[[Nsclassfromstring (ClassName) alloc]init]; //Get Class object    IDClassobject =Objc_getclass ([ClassName utf8string]); unsignedintCount =0; objc_property_t*properties = Class_copypropertylist (Classobject, &count); Ivar*ivars =class_copyivarlist (classobject, nil);  for(inti =0; I < count; i + +) {        //Get member nameNSString *membername =[NSString stringwithutf8string:ivar_getname (Ivars[i])]; Const Char*type =ivar_gettypeencoding (Ivars[i]); NSString*datatype =[NSString Stringwithcstring:type encoding:nsutf8stringencoding]; NSLog (@"Data%@ Type:%@", Membername,datatype); Hybjsonmodeldatatype Rtype=Khybjsonmodeldatatypeobject; if([DataType Hasprefix:@"C"]) {Rtype= Khybjsonmodeldatatypebool;//BOOL}Else if([DataType Hasprefix:@"I"]) {Rtype= Khybjsonmodeldatatypeinteger;//int}Else if([DataType Hasprefix:@"F"]) {Rtype= Khybjsonmodeldatatypefloat;//float}Else if([DataType Hasprefix:@"D"]) {Rtype= khybjsonmodeldatatypedouble;//Double}Else if([DataType Hasprefix:@"L"]) {Rtype= Khybjsonmodeldatatypelong;//Long        }                 for(intj =0; J < Count; J + +) {objc_property_t property=Properties[j]; NSString*propertyname =[[NSString alloc] Initwithcstring:property_getname (property)            Encoding:nsutf8stringencoding]; Nsrange Range=[MemberName Rangeofstring:propertyname]; if(Range.location = =nsnotfound) {                Continue; } Else {                IDPropertyValue =[Dict Objectforkey:propertyname]; Switch(rtype) { Casekhybjsonmodeldatatypebool: {BOOL temp= [[NSString stringWithFormat:@"%@", PropertyValue] boolvalue]; PropertyValue=[NSNumber numberwithbool:temp]; }                         Break;  CaseKhybjsonmodeldatatypeinteger: {inttemp = [[NSString stringWithFormat:@"%@", PropertyValue] intvalue]; PropertyValue=[NSNumber numberwithint:temp]; }                         Break;  Casekhybjsonmodeldatatypefloat: {floattemp = [[NSString stringWithFormat:@"%@", PropertyValue] floatvalue]; PropertyValue=[NSNumber numberwithfloat:temp]; }                         Break;  Casekhybjsonmodeldatatypedouble: {Doubletemp = [[NSString stringWithFormat:@"%@", PropertyValue] doublevalue]; PropertyValue=[NSNumber numberwithdouble:temp]; }                         Break;  CaseKhybjsonmodeldatatypelong: {Long Longtemp = [[NSString stringWithFormat:@"%@", PropertyValue] longlongvalue]; PropertyValue=[NSNumber numberwithlonglong:temp]; }                         Break; default:                         Break;                } [model Setvalue:propertyvalue forkey:membername];  Break; }        }    }    returnmodel;}@end

IOS dictionary and model convert each other

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.