ios XML,JSON,數組解析並轉換成NSMutableArray(List<class>)

來源:互聯網
上載者:User

標籤:xml   json   數組   資料解析   Regex   

一、簡介

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


ios XML,JSON,數組解析並轉換成NSMutableArray(List<class>)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.