1. 程式人生 > >ios XML,JSON,陣列解析並轉換成NSMutableArray(List)

ios XML,JSON,陣列解析並轉換成NSMutableArray(List)

一、簡介

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,陣列解析轉換NSMutableArrayList

一、簡介 JSON解析: 通過正則將JSON([{...},{...}...])分解成多個包含實體例項內容的一小節({...}),在一小節中通過Runtime(執行時)(<objc/runtime.h>)將實體所有屬性值找到並賦值(正則查詢實現)到例項({...

ios 獲取當前時間,轉換時間戳

1.獲取當前時間 +(NSString *)getCurrentDate {     //獲取當前時間     NSDate *now = [NSDate date];     KELog(@"now date is: %@", now);          NSCalen

Jackson將json字符串轉換泛型List

str json數組 std cer time stl cond exc obj 情景: 需求,需要做一個接口,請求體中的參數是string類型。 參數是一個批量的數據,json數組格式,所以需要把string的參數轉換成list類型。 參數如下: [ {

字串轉換整數Java

題目:字串轉換為整數。 思路:將字串轉化為整數首先是遍歷字串中的每一個字元,有三種情況:首字元是正號,首字元是負號,首字元非正負號;然後遍歷每一個字元進行num = num * 10 + charAr

字串轉換整數atoi函式的具體實現

程式碼如下: #include "stdio.h" int Atoi(char* str) {int sum=0;while(*str!='\0'){if (*str>='0' && *str<='9'){sum=sum*10+*str-'0';

將DataTable與DataView轉換DataSet示例

今天遇到這樣的事情。將DataSet的檢視傳遞給DataView,對DataView進行了資料排序。然後想將 DataView再放到DataSet中。卻發現,DataSet的檢視狀態是不可以賦值的。即是隻讀狀態。  當然頭一個反應就是到百度上去搜索。以“DataView轉換成

把字串轉換整數字串

題目描述:將一個字串轉換成一個整數,要求不能使用字串轉換整數的庫函式。 數值為0或者字串不是一個合法的數值則返回0。 輸入描述:輸入一個字串,包括數字字母符號,可以為空 輸出描述:如果是合法的數值表達則返回該數字,否則返回0  思路一: public class Solu

將列表list的資料寫到csv 裡面+ 讀取csv檔案裡面的資料寫到列表list裡面

將列表(list)的資料寫到csv 裡面 import pandas as pd file_path = 'file_path' image_id = [397133, 37777, 252219, 87038] name=['imageid'] test=pd.DataFrame(col

iOS開發之JSON轉PLIST把存儲json格式的文件轉換plist文件

string 數據 導致 atom use error: ali ror 進行 有時開發過程中,經常需要調試接口,但是可能經常沒有網絡,導致調試無法正常進行。 對此可以自己手動設置一些假數據,也可以通過計算機來為我們保存一份真實的網絡數據,並自己轉化成plist數據,

c++ 解析從瀏覽器端傳過來的影象base64編碼,轉換opencv識別的格式

#include <cstdint> #include <fstream> #include <iostream> #include <string> #include <vector> #includ

java讀取xml檔案轉換物件,進行修改

1.首先要寫工具類,處理讀取和寫入xml檔案使用的工具。XMLUtil.java import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import j

JSON.parseArray():將json格式的資料轉換陣列格式

1、這個方法的作用就是將json格式的資料轉換成陣列格式。 2、假設有Person這個類,有json型別資料jsonStr = [{"name":"張三","age":"1"},{"name":"李四","age":"4"}],那麼 List lists = json.p

iOS ---對json陣列解析

小括號是陣列 大括號是字典 NSMutableArray *arr =[NSMutableArrayarray]; NSMutableArray *arr1 =[NSMutableArra

【jquery】通過【ajax】獲取資料轉換Json

頁面程式碼:<head runat="server"> <title></title> <script src="jquery-1.4.2.min.js" type="text/javascript"><

JSON字符串轉換JSON對象

script 如果 with 方法 rom code ie8 eva fire 一 JSON對象的parse方法 IE8+、Chrome、Safari、Firefox瀏覽器都支持。 var str = ‘{"name":"張三"}‘; var obj = J

[轉載]將json字符串轉換json對象

新版 函數 就是 ron ast 接下來 對象 obj 壓縮 例如: JSON字符串: var str1 = ‘{ "name": "cxh", "sex": "man" }‘; JSON對象: var str2 = { "name": "cxh", "sex": "ma

json字符串轉換json對象,json對象轉換字符串,值轉換字符串,字符串轉

兩個 負數 相關 5.6 對象 style pre www. 進行 主要內容: 一、json相關概念 二、json字符串轉換成json對象 (字符串-->JSON對象) 三、json對象轉換成字符串(json對象-->字符串) 四、將值轉換成字符串(值-

Jackson將json字符串轉換List<JavaBean>

ray 註意 編譯 new pub gpo body get ont public final ObjectMapper mapper = new ObjectMapper(); public static void main(String[] args)

.net core2.0添加json文件轉化類註入控制器使用

serialize don 程序 發現 tex mod onf -s 既然   上一篇,我們介紹了如何讀取自定義的json文件,數據是讀取出來了,只是處理的時候太麻煩,需要一遍一遍寫,很枯燥.那麽有沒有很好的辦法呢?經過鉆研,辦法有了.   既然一個一個讀取比較麻煩,那麽可

Ubuntu下錄製螢幕轉換gif

    日常工作中,經常需要將錄製的視訊(.mp4/.ogv/avi/…)轉換成gif動圖。隨便舉個例子,同學們在使用部落格記錄東西的時候常常需要演示應用程式在手機上的執行效果,通常這些效果都是被以視訊格式來進行儲存的。而往往markdown編輯器不允許上傳視訊,因此我們常常需要將視訊格式的