ios XML,JSON,配列を解析しNSMutableArray(List)に変換する<br>)


一、紹介
JSON解析:
JSON([{...}{...}...])エンティティインスタンスの内容を含む複数のセクション({...})に分解し、エンティティのすべての属性値をRuntime()を使用してインスタンス({...}-->エンティティのインスタンス).すべてのセクション({...})を巡回します.XMLをNSMutableArray(List)に変換します.
XML解析:
XMLは、GDataXml(または正規)によって複数のエンティティインスタンスの内容を含む小さなセクションXMLに分解され、小さなセクションでRuntime(実行時)()によってエンティティのすべての属性値が見つかり、インスタンスに値が割り当てられ(正規検索実装)、あるセクションを巡ってXMLがNSMutableArray(List)に変換される.
配列解析:
XMLをつなぎ合わせ、GDataXmlでXMLをNSMutableArray(List)に変換します(プロセス全体を正規化することもできます).
3つの解析方法を共通クラス(GlobalApplication)に記述しました
実装方法に2つのヘッダファイルを追加することに注意してください.
#import <objc/runtime.h>
#import "GDataXMLNode.h"

使用方法:
    // User        
    // xml --> NSMutableArray (List<class>)
    NSMutableArray *retVal = [GlobalApplication jsonToArray:xml class:User.class];
    // xml --> NSMutableArray (List<class>)
    NSMutableArray *retVal = [GlobalApplication xmlToArray:xml class:User.class rowRootName:@"row"];
    // xml --> NSMutableArray (List<String>)
    NSMutableArray *retVal = [GlobalApplication xmlToArray:xml];

二、コード
1、GlobalApplication.h
//
//  GlobalApplication.h
//  WebServcieBySoap
//
//  Created by fengs on 14-11-19.
//  Copyright (c) 2014  fengs. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface GlobalApplication : NSObject

#pragma mark -
#pragma mark -  xml(  )   NSMutableArray (List<String>)
/**
 *  xml(  )   NSMutableArray
 * @param xml
     <string>fs</string>
     <string>fs</string>
     ...
 * @return NSMutableArray (List<String>)
 */
+(NSMutableArray*)xmlToArray:(NSString*)xml;

#pragma mark -
#pragma mark -     xml(  )   NSMutableArray (List<class>)
/**
 *     xml(  )   NSMutableArray
 * @param xml:
     <data xmlns="">
     <row><UserID>ff0f0704</UserID><UserName>fs</UserName></row>
     <row><UserID>ff0f0704</UserID><UserName>fs</UserName></row>
     ......
     </data>
 * @param class:
    User
 * @param rowRootName:
    row
 * @return NSMutableArray (List<class>)
 */
+(NSMutableArray*)xmlToArray:(NSString*)xml class:(Class)class rowRootName:rowRootName;

#pragma mark -
#pragma mark -     Json(  )   NSMutableArray (List<class>)
/**
 *     xml(  )   NSMutableArray
 * @param xml:
    [{"UserID":"ff0f0704","UserName":"fs"},
    {"UserID":"ff0f0704","UserName":"fs"},...]
 * @param class:
    User
 * @return NSMutableArray (List<class>)
 */
+(NSMutableArray*)jsonToArray:(NSString*)json class:(Class)class;
@end

2、GlobalApplication.m
//
//  GlobalApplication.m
//  WebServcieBySoap
//
//  Created by fengs on 14-11-19.
//  Copyright (c) 2014  fengs. All rights reserved.
//

#import "GlobalApplication.h"
#import <objc/runtime.h>
#import "GDataXMLNode.h"

@implementation GlobalApplication

#pragma mark - 
#pragma mark -  xml(  )   NSMutableArray (List<String>)
/**
 *  xml(  )   NSMutableArray
 * @param xml
     <string>fs</string>
     <string>fs</string>
     ...
 * @return NSMutableArray (List<String>)
 */
+(NSMutableArray*)xmlToArray:(NSString*)xml{
    
    NSMutableArray *retVal = [[[NSMutableArray alloc] init] autorelease];
    xml = [NSString stringWithFormat:@"<data>%@</data>",xml];
    GDataXMLDocument *root = [[[GDataXMLDocument alloc] initWithXMLString:xml options:0 error:nil] autorelease];
    GDataXMLElement *rootEle = [root rootElement];
    for (int i=0; i <[rootEle childCount]; i++) {
        GDataXMLNode *item = [rootEle childAtIndex:i];
        [retVal addObject:item.stringValue];
    }
    return retVal;
}

#pragma mark -
#pragma mark -     xml(  )   NSMutableArray (List<class>)
/**
 *     xml(  )   NSMutableArray
 * @param xml:
     <data xmlns="">
     <row><UserID>ff0f0704</UserID><UserName>fs</UserName></row>
     <row><UserID>ff0f0704</UserID><UserName>fs</UserName></row>
     ......
     </data>
 * @param class:
     User
 * @param rowRootName:
     row
 * @return NSMutableArray (List<class>)
 */
+(NSMutableArray*)xmlToArray:(NSString*)xml class:(Class)class rowRootName:rowRootName{
    
    NSMutableArray *retVal = [[[NSMutableArray alloc] init] autorelease];
    GDataXMLDocument *root = [[[GDataXMLDocument alloc] initWithXMLString:xml options:0 error:nil] autorelease];
    GDataXMLElement *rootEle = [root rootElement];
    NSArray *rows = [rootEle elementsForName:rowRootName];
    for (GDataXMLElement *row in rows) {
        id object = [[class alloc] init];
        object = [self initWithXMLString:row.XMLString object:object];
        [retVal addObject:object];
        [object release];
    }
    return retVal;
}

/**
 *           
 * @param xml(           ):
    <row><UserID>ff0f0704</UserID><UserName>fs</UserName></row>
 * @param class:
    User @property userName,userID;
 * @return class
 */
+(id)initWithXMLString:(NSString*)xml object:(id)object{
    
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([object class], &outCount);
    for (i = 0; i<outCount; i++)
    {
        objc_property_t property = properties[i];
        const char* char_f = property_getName(property);
        NSString *propertyName = [NSString stringWithUTF8String:char_f];
        NSString *value = [self setXMLProperty:xml propertyName:propertyName];
        [object setValue:value forKey:propertyName];
    }
    free(properties);
    
    return object;
}

/**
 *               
 * @param content(           ):
    <row><UserID>ff0f0704</UserID><UserName>fs</UserName></row>
 * @param propertyName:
    userID
 * @return NSString
    ff0f0704
 */
+(NSString*)setXMLProperty:(NSString*)value propertyName:(NSString*)propertyName {
    
    NSString *retVal = @"";
    NSString *patternString = [NSString stringWithFormat:@"(?<=<%@>)(.*)(?=</%@>)",propertyName,propertyName];
    // CaseInsensitive:        
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:patternString options:NSRegularExpressionCaseInsensitive error:nil];
    if (regex) {
        NSTextCheckingResult *firstMatch = [regex firstMatchInString:value options:NSCaseInsensitiveSearch range:NSMakeRange(0, [value length])];
        if (firstMatch) {
            retVal = [value substringWithRange:firstMatch.range];
        }
    }
    return retVal;
}

#pragma mark -
#pragma mark -     Json(  )   NSMutableArray (List<class>)
/**
 *     Json(  )   NSMutableArray
 * @param xml:
     [{"UserID":"ff0f0704","UserName":"fs"},
      {"UserID":"ff0f0704","UserName":"fs"},...]
 * @param class:
    User
 * @return NSMutableArray (List<class>)
 */
+(NSMutableArray*)jsonToArray:(NSString*)json class:(Class)class {
    
    NSMutableArray *retVal = [[[NSMutableArray alloc] init] autorelease];
    NSString *patternString = @"\\{.*?\\}";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:patternString options:0 error:nil];
    if (regex) {
        NSArray *match = [regex matchesInString:json options:0 range:NSMakeRange(0, [json length])];
        if (match) {
            for (NSTextCheckingResult *result in match) {
                NSString *jsonRow = [json substringWithRange:result.range];
                id object = [[class alloc] init];
                object = [self initWithJsonString:jsonRow object:object];
                [retVal addObject:object];
                [object release];
            }
        }
    }
    return retVal;
}

/**
 *           
 * @param xml(         ):
    {"UserID":"ff0f0704","UserName":"fs"}
 * @param class:
    User @property userName,userID;
 * @return class
 */
+(id)initWithJsonString:(NSString*)json object:(id)object{
    
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([object class], &outCount);
    for (i = 0; i<outCount; i++)
    {
        objc_property_t property = properties[i];
        const char* char_f = property_getName(property);
        NSString *propertyName = [NSString stringWithUTF8String:char_f];
        NSString *value = [self setJsonProperty:json propertyName:propertyName];
        [object setValue:value forKey:propertyName];
    }
    free(properties);
    
    return object;
}

/**
 *               
 * @param content(         ):
    {"UserID":"ff0f0704","UserName":"fs"}
 * @param propertyName:
    userID
 * @return NSString
    ff0f0704
 */
+(NSString*)setJsonProperty:(NSString*)value propertyName:(NSString*)propertyName {

    NSString *retVal = @"";
    NSString *patternString = [NSString stringWithFormat:@"(?<=\"%@\":\")[^\",]*",propertyName];
    // CaseInsensitive:        
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:patternString options:NSRegularExpressionCaseInsensitive error:nil];
    if (regex) {
        NSTextCheckingResult *firstMatch = [regex firstMatchInString:value options:NSCaseInsensitiveSearch range:NSMakeRange(0, [value length])];
        if (firstMatch) {
            retVal = [value substringWithRange:firstMatch.range];
        }
    }
    return retVal;
}
@end