MJExtension Documentation

repository·master·Indexed 27 days ago

https://github.com/codermjlee/mjextension

A 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.

Tokens
2.4K
Snippets
14
Records
18
Agent score
44%

What's inside MJExtension

  1. Overview of MJExtension

    master
    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.
  2. Features of MJExtension

    master

    MJExtension provides the following conversion capabilities:

    • JSON to Model: Convert JSON or JSONString to a Model or Core Data Model.
    • Model to JSON: Convert a Model or Core Data Model to JSON.
    • Arrays: Convert JSON Array or JSONString to Model Array or Core 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.
  3. Use MJExtension in Swift

    master

    To use MJExtension in Swift projects, you must ensure properties are accessible to Objective-C.

    1. Add @objc or @objcMembers to the class or individual properties.
    2. For basic types like Bool and Int, you must use the dynamic attribute, ensure they are Non-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?
    }
  4. Implement Secure Coding (NSSecureCoding) with MJExtension

    master

    For NSSecureCoding support, use the MJSecureCodingImplementation(class, isSupport) macro.

    @import MJExtension;
    
    // NSSecureCoding Implementation
    MJSecureCodingImplementation(MJBag, YES)
    
    @implementation MJBag
    @end
  5. Convert Dictionary to Model using `mj_objectWithKeyValues:`

    master

    Use the mj_objectWithKeyValues: method to transform a NSDictionary into a model object. This handles basic type conversion (e.g., strings to numbers or booleans).

    // JSON -> User
    User *user = [User mj_objectWithKeyValues:dict];
  6. Implement Coding (NSCoding) with MJExtension

    master

    To support NSCoding (archiving/unarchiving), add the MJCodingImplementation macro to your model. You can also use mj_setupIgnoredCodingPropertyNames: to exclude specific properties from being encoded.

    @implementation MJBag
    MJCodingImplementation
    @end
    
    // what properties not to be coded
    [MJBag mj_setupIgnoredCodingPropertyNames:^NSArray *{ 
        return @[@"name"]; 
    }];
  7. Use MJExtension with Core Data

    master

    MJExtension 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()
        }
    }
  8. Convert Model Array to JSON Array using `mj_keyValuesArrayWithObjectArray:`

    master

    To transform an array of model objects into an array of dictionaries, use mj_keyValuesArrayWithObjectArray:.

    // Model array -> JSON array
    NSArray *dictArray = [User mj_keyValuesArrayWithObjectArray:userArray];
  9. Customize Value Transformation with `mj_newValueFromOldValue:property:`

    master

    To perform custom transformations during JSON -> Model conversion (e.g., converting a String to an NSDate or handling nil values), override mj_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;
    }
  10. Customize Model to Dictionary conversion with `mj_objectDidConvertToKeyValues:`

    master
    To modify how properties are represented when converting a Model back to a Dictionary (e.g., converting an NSDate to a formatted NSString), override mj_objectDidConvertToKeyValues:.
  11. Convert JSON String to Model using `mj_objectWithKeyValues:`

    master

    The mj_objectWithKeyValues: method also accepts an NSString containing 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];