MJExtension Documentation
repository·master·Indexed 27 days ago
https://github.com/codermjlee/mjextensionA high-performance, lightweight framework for iOS and macOS that facilitates bidirectional conversion between JSON data (dictionaries and strings) and data models, including support for Core Data. It provides capabilities for JSON-to-model and model-to-JSON conversion, handling of model arrays, and simplified implementation of NSCoding and NSSecureCoding.
What's inside MJExtension
- MJExtension is a fast, lightweight, and non-intrusive framework designed for converting between JSON and models (including Core Data models). It supports bidirectional conversion between dictionaries, JSON strings, and model arrays.
Features of MJExtension
masterMJExtension provides the following conversion capabilities:
- JSON to Model: Convert
JSONorJSONStringto aModelorCore Data Model. - Model to JSON: Convert a
ModelorCore Data ModeltoJSON. - Arrays: Convert
JSON ArrayorJSONStringtoModel ArrayorCore Data Model Array, and vice versa. - Coding/Secure Coding: Perform coding/secure coding on all properties of a model with a single line of code.
- JSON to Model: Convert
Use MJExtension in Swift
masterTo use MJExtension in Swift projects, you must ensure properties are accessible to Objective-C.
- Add
@objcor@objcMembersto the class or individual properties. - For basic types like
BoolandInt, you must use thedynamicattribute, ensure they areNon-Optional, and provide an initial default value.
If your project is purely Swift, the author recommends using KakaJSON instead.
@objc(MJTester) @objcMembers class MJTester: NSObject { // make sure to use `dynamic` attribute for basic type & must use as Non-Optional & must set initial value dynamic var isSpecialAgent: Bool = false dynamic var age: Int = 0 var name: String? var identifier: String? }- Add
Install MJExtension
masterYou can install MJExtension using CocoaPods, Carthage, Swift Package Manager, or by manual integration.Implement Secure Coding (NSSecureCoding) with MJExtension
masterFor
NSSecureCodingsupport, use theMJSecureCodingImplementation(class, isSupport)macro.@import MJExtension; // NSSecureCoding Implementation MJSecureCodingImplementation(MJBag, YES) @implementation MJBag @endConvert Dictionary to Model using `mj_objectWithKeyValues:`
masterUse the
mj_objectWithKeyValues:method to transform aNSDictionaryinto a model object. This handles basic type conversion (e.g., strings to numbers or booleans).// JSON -> User User *user = [User mj_objectWithKeyValues:dict];Implement Coding (NSCoding) with MJExtension
masterTo support
NSCoding(archiving/unarchiving), add theMJCodingImplementationmacro to your model. You can also usemj_setupIgnoredCodingPropertyNames:to exclude specific properties from being encoded.@implementation MJBag MJCodingImplementation @end // what properties not to be coded [MJBag mj_setupIgnoredCodingPropertyNames:^NSArray *{ return @[@"name"]; }];Use MJExtension with Core Data
masterMJExtension provides support for Core Data. Use
mj_object(withKeyValues:context:)to create Core Data objects from dictionaries within a context.func json2CoreDataObject() { context.performAndWait { let object = MJCoreDataTester.mj_object(withKeyValues: Values.testJSONObject, context: context) } } func coreDataObject2JSON() { context.performAndWait { let dict = coreDataObject.mj_keyValues() } }Convert Model Array to JSON Array using `mj_keyValuesArrayWithObjectArray:`
masterTo transform an array of model objects into an array of dictionaries, use
mj_keyValuesArrayWithObjectArray:.// Model array -> JSON array NSArray *dictArray = [User mj_keyValuesArrayWithObjectArray:userArray];Customize Value Transformation with `mj_newValueFromOldValue:property:`
masterTo perform custom transformations during JSON -> Model conversion (e.g., converting a String to an
NSDateor handlingnilvalues), overridemj_newValueFromOldValue:property:.- (id)mj_newValueFromOldValue:(id)oldValue property:(MJProperty *)property { if ([property.name isEqualToString:@"publisher"]) { if (oldValue == nil) return @""; } else if (property.type.typeClass == [NSDate class]) { NSDateFormatter *fmt = [[NSDateFormatter alloc] init]; fmt.dateFormat = @"yyyy-MM-dd"; return [fmt dateFromString:oldValue]; } return oldValue; }Customize Model to Dictionary conversion with `mj_objectDidConvertToKeyValues:`
masterTo modify how properties are represented when converting a Model back to a Dictionary (e.g., converting anNSDateto a formattedNSString), overridemj_objectDidConvertToKeyValues:.Convert JSON String to Model using `mj_objectWithKeyValues:`
masterThe
mj_objectWithKeyValues:method also accepts anNSStringcontaining a JSON string and converts it directly into a model object.// 1.Define a JSONString NSString *jsonString = @"{\"name\":\"Jack\", \"icon\":\"lufy.png\", \"age\":20}"; // 2.JSONString -> User User *user = [User mj_objectWithKeyValues:jsonString];