iOS json格式轉換

2021-07-02 14:46:30 字數 1824 閱讀 1729

nsstring *str = nil;

//字串

nsmutablestring *string = [[nsmutablestring alloc] init];

str = [string jsonstring];

nslog(@"str1:%@",[nsstring stringwithstring:str]);

//陣列

nsarray *array = [[nsarray alloc] initwithobjects:@"111",@"333",@"222", nil];

// nsmutablearray *array = [nsmutablearray array];

str = [array jsonstring];

nslog(@"str2:%@",[nsstring stringwithstring:str]);

[array release ];

//字典

nsarray *firstarr = [nsarray arraywithobjects:@"first",@"second", nil];

//基本資料型別轉換成nsnumber型別

nsarray *secondarr = [nsarray arraywithobjects:[nsnumber numberwithdouble:2.1],[nsnumber numberwithbool:no], nil];

//加到字典中

nsdictionary *dic = [nsdictionary dictionarywithobjectsandkeys:firstarr,@"first",secondarr,@"second", nil];

//轉化成json格式

str = [dic jsonstring];

nsstring *str2 = [nsstring stringwithstring:str];

nslog(@"str3:%@",str2);

//編碼

nsdata *archive = [nskeyedarchiver archiveddatawithrootobject:array];

// nslog(@"archive:%@",archive);

nsarray *arr2 = [nskeyedunarchiver unarchiveobjectwithdata:archive];

nslog(@"arr2:%@",arr2);

/*!* @brief 把格式化的json格式的字串轉換成字典

* @param jsonstring json格式的字串

* @return 返回字典

*/+ (nsdictionary *)dictionarywithjsonstring:(nsstring *)jsonstring

nsdata *jsondata = [jsonstring datausingencoding:nsutf8stringencoding];

nserror *err;

nsdictionary *dic = [nsjsonserialization jsonobjectwithdata:jsondata

options:nsjsonreadingmutablecontainers

error:&err];

if(err)

return dic;

}+ (nsstring*)dictionarytojson:(nsdictionary *)dic

iOS JSON資料格式

json格式 1大括號代表字典 2中括號 小括號 代表陣列 3冒號的左右兩邊分別為鍵和值 key value 4資料和資料之間用逗號隔開 json解析 例 取出名字abc nsstring jstr 你可能一開始獲得的是乙個字串,比如讀檔案內容 1 因為最外面是字典,所以需要用字典型別物件來接 ns...

iOS JSON 模型轉換庫評測

ios 開發中總會用到各種 json 模型轉換庫,這篇文章將會對常見的幾個開源庫進行一下評測。評測的內容主要集中在效能 功能 容錯性這幾個方面。manually 手動進行 json model 轉換,不用任何開源庫,可以進行高效 自由的轉換,但手寫 非常繁瑣,而且容易出錯。yymodel 我造的乙個...

iOS JSON 模型轉換庫評測

ios 開發中總會用到各種 json 模型轉換庫,這篇文章將會對常見的幾個開源庫進行一下評測。評測的內容主要集中在效能 功能 容錯性這幾個方面。manually 手動進行 json model 轉換,不用任何開源庫,可以進行高效 自由的轉換,但手寫 非常繁瑣,而且容易出錯。yymodel 我造的乙個...