ios XML,JSON,数组解析并转换成NSMutableArray(List<class>)

一、简介

JSON解析:

通过正则将JSON([{...},{...}...])分解成多个包含实体实例内容的一小节({...}),在一小节中通过Runtime(运行时)(<objc/runtime.h>)将实体所有属性值找到并赋值(正则查找实现)到实例({...} --> 实体的一个实例),遍历所有小节({...})就将XML转换成NSMutableArray(类似:List<class>)

XML 解析:

通过GDataXml(也可以通过正则)将XML分解成多个包含实体实例内容的一小节XML,在一小节中通过Runtime(运行时)(<objc/runtime.h>)将实体所有属性值找到并赋值(正则查找实现)到实例,遍历所有小节将XML转换成NSMutableArray(类似:List<class>)

数组解析:

将XML拼接,通过GDataXml将XML转换成NSMutableArray(类似:List<string>)(整个过程也可以通过正则实现)

已将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


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。