您的位置:首页 > 移动开发 > IOS开发

iOS/Android JSON封包与解包

2016-07-21 19:55 411 查看


一、iOS JSON封包与解包


iOS自带的JSON解决方案(NSJSONSerialization),它提供了针对NSDictionary、NSArray对象进行JSON数据的封包和解包。

1、JSON封包:

针对NSDictionary:

NSDictionary *mDic =[[NSDictionaryalloc]initWithObjectsAndKeys:@"Hello world", @"Hello";

NSData *jsonData = [NSJSONSerializationdataWithJSONObject:mDic options:0error:nil];

NSString *sendString = [[NSStringalloc]initWithData:jsonDataencoding:NSUTF8StringEncoding];

针对NSArray:

NSArray *mArray = [[NSMutableArrayalloc] init;

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mArray options:0 error:nil];

NSString *sendString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

注:通过NSDictionary、NSArray的各种组合可以组件复杂的JSON格式数据

2、JSON解包:

针对NSDictionary:

NSString *mFilePath =@"./jsonData.json";

NSData *jsonData = [NSDatadataWithContentsOfFile:mFilePath];

NSDictionary *jsonDict = [NSJSONSerializationJSONObjectWithData:jsonDataoptions: NSJSONReadingMutableContainerserror:nil];

针对NSArray:

NSString *mFilePath = @"./jsonData.json";

NSData *jsonData = [NSData dataWithContentsOfFile:mFilePath];

NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error:nil];

二、Android JSON封包与解包


Android自带的JSON解决方案(JSONObject、JSONStringer、JSONArray)

1、JSON封包

JSONObject jsonObject = new JSONObject();

JSONArray jsonArray = new JSONArray();

jsonArray.put("DeviceID").put("DeviceName");

jsonObject.put("jsonArray", jsonArray);

2、JSON解包:

private static final String strJSON = "...";

JSONTokener jsonParser = new JSONTakener(strJSON);

JSObject jsonObject = (JSONObject)jsonParser.nextValue();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: