iOS开发——网络编程OC篇&数据解析总结

数据解析总结

 

  1 //***************************************************XML

  2 

  3 /**

  4 NSXML

  5 */

  6 /**

  7 // 1. 开始解析XML文档

  8 - (void)parserDidStartDocument:

  9 

 10 // 2. 开始解析某个元素,会遍历整个XML,识别元素节点名称

 11 - (void)parser:didStartElement:namespaceURI:qualifiedName:attributes:

 12 // 3. 文本节点,得到文本节点里存储的信息数据,对于大数据可能会接收多次!为了节约内存开销

 13 - (void)parser:foundCharacters:

 14 // 4. 结束某个节点,存储从parser:foundCharacters:方法中获取到的信息

 15 - (void)parser:didEndElement:namespaceURI:qualifiedName:

 16 注意:在解析过程中,2、3、4三个方法会不停的重复执行,直到遍历完成为止

 17 

 18 // 5. 解析XML文档结束

 19 - (void)parserDidEndDocument:

 20 // 6. 解析出错

 21 - (void)parser:parseErrorOccurred:

 22 

 23 

 24 

 25 @interface ALViewController ()

 26 

 27 @property (nonatomic, strong) NSMutableArray *dataList;

 28 // 来回拼接

 29 @property (nonatomic, strong) NSMutableString *elementString;

 30 // 当前视频信息的对象

 31 @property (nonatomic, strong) Video *v;

 32 

 33 @end

 34 

 35 @implementation MJViewController

 36 

 37 - (void)viewDidLoad

 38 {

 39 [super viewDidLoad];

 40 

 41 // 加载数据方法

 42 [self loadData];

 43 }

 44 

 45 #pragma mark - 表格的数据源方法

 46 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

 47 {

 48 return self.dataList.count;

 49 }

 50 

 51 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

 52 {

 53 // 1.创建cell

 54 static NSString *ID = @"CELL";

 55 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

 56 

 57 // 2.设置cell的数据

 58 Video *v = self.dataList[indexPath.row];

 59 

 60 cell.textLabel.text = v.name;

 61 

 62 return cell;

 63 }

 64 

 65 #pragma mark - 加载数据

 66 - (IBAction)loadData

 67 {

 68 // 1. URL

 69 NSURL *url = [NSURL URLWithString:@"http://localhost/videos.php"];

 70 // 2. Request

 71 NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:10.0f];

 72 

 73 // 开始显示刷新控件

 74 [self.refreshControl beginRefreshing];

 75 

 76 // 3. 发送请求

 77 [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init]completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

 78 

 79 // 1>

 80 NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];

 81 

 82 // 2> 设置代理

 83 parser.delegate = self;

 84 

 85 // 3> 开始解析

 86 [parser parse];

 87 }];

 88 }

 89 

 90 #pragma mark - XML解析代理方法

 91 #pragma mark 1. 开始

 92 - (void)parserDidStartDocument:(NSXMLParser *)parser

 93 {

 94 NSLog(@"开始解析文档");

 95 // 准备工作

 96 // 1> dataList

 97 if (!self.dataList) {

 98 self.dataList = [NSMutableArray array];

 99 } else {

100 [self.dataList removeAllObjects];

101 }

102 

103 // 2> elementString

104 if (!self.elementString) {

105 self.elementString = [NSMutableString string];

106 } else {

107 // 清空可变字符串不要设置成nil,使用setString只是清空内容,下次不会再次实例化

108 [self.elementString setString:@""];

109 }

110 }

111 

112 #pragma mark 2. 所有开始一个节点:

113 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict

114 {

115 NSLog(@"开始节点:%@ %@", elementName, attributeDict);

116 // 如果是新建对象

117 if ([elementName isEqualToString:@"video"]) {

118 self.v = [[Video alloc] init];

119 self.v.videoId = attributeDict[@"videoId"];

120 }

121 

122 // 每开始一个新节点之前都清空elementString

123 // 避免上一次的结果被重复拼接,例如拼完名字是"abc",再拼长度就会变成"vda1234"

124 [self.elementString setString:@""];

125 }

126 

127 #pragma mark 3. 查找内容,可能会重复多次

128 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string

129 {

130 // 拼接字符串

131 [self.elementString appendString:string];

132 }

133 

134 #pragma mark 4. 节点结束

135 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName

136 {

137 NSLog(@"结束节点 %@", elementName);

138 // 判断如果是要复制

139 if ([elementName isEqualToString:@"video"]) {

140 [self.dataList addObject:self.v];

141 } else if (![elementName isEqualToString:@"videos"]) {

142 [self.v setValue:self.elementString forKey:elementName];

143 }

144 // 提示:使用KVC只要是数值型的属性,kvc会自动设置成对应的属性,而无需程序员参与

145 //    if ([elementName isEqualToString:@"name"]) {

146 //        self.v.name = self.elementString;

147 //    } else if ([elementName isEqualToString:@"length"]) {

148 //        self.v.length = [NSNumber numberWithInt:[self.elementString intValue]];

149 //    }

150 }

151 

152 #pragma mark 5. 文档结束

153 - (void)parserDidEndDocument:(NSXMLParser *)parser

154 {

155 NSLog(@"解析结束 %@ %@", self.dataList, [NSThread currentThread]);

156 

157 dispatch_async(dispatch_get_main_queue(), ^{

158 [self.tableView reloadData];

159 

160 // 关闭刷新控件的刷新

161 [self.refreshControl endRefreshing];

162 });

163 //    [self.dataList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

164 //        NSLog(@"%@", obj);

165 //    }];

166 }

167 

168 #pragma mark 6. 出错处理

169 - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError

170 {

171 NSLog(@"%@", parseError.localizedDescription);

172 }

173 

174 

175 @end

176 */

177 

178 

179 

180 /**

181 TBXML

182 */

183 /**

184 //解析代码

185 - (void)testTBXM:(TBXML *)tbx {

186 TBXMLElement *root = tbx.rootXMLElement;

187 TBXMLElement *author = [TBXML childElementNamed:@"author" parentElement:root];

188 NSString *name = [TBXML valueOfAttributeNamed:@"name" forElement:author];

189 NSLog(@"author:%@", name);

190 TBXMLElement *book = [TBXML childElementNamed:@"book" parentElement:author];

191 TBXMLElement *descriptionElem = [TBXML childElementNamed:@"description" parentElement:book];

192 NSString * description = [TBXML textForElement:descriptionElem];

193 NSLog(@"author:%@", description);

194 }

195 

196 2.递归解析未知结构的xml。

197 

198 //主调用方法

199 

200 - (void)dealUnknow:(TBXML *)tbx {

201 if (tbx.rootXMLElement) {

202 TBXMLElement *element = tbx.rootXMLElement;

203 [self recurrence:element];

204 }

205 else {

206 NSLog(@"Format Error!");

207 }

208 }

209 

210 //递归子方法

211 

212 - (void)recurrence:(TBXMLElement *)element {

213 do {

214 

215 NSLog(@"<%@>:{%@}",[TBXML elementName:element], [TBXML textForElement:element]);// Display the name of the element

216 

217 //迭代处理所有属性

218 TBXMLAttribute * attribute = element->firstAttribute;

219 while (attribute) {

220 //显示

221 NSLog(@"<%@>->[%@ = %@]", [TBXML elementName:element], [TBXML attributeName:attribute], [TBXML attributeValue:attribute]);

222 //迭代

223 attribute = attribute->next;

224 }

225 

226 //递归处理子树

227 if (element->firstChild) {

228 [self recurrence:element->firstChild];

229 }

230 

231 //迭代处理兄弟树

232 } while ((element = element->nextSibling));

233 }

234 

235 总之,tbxml解析xml飞速、简洁,可惜不能操作回写,仅陷于解析,做rss巨合适不过了!

236 

237 如想进步了解,请参加下篇,tbxml常用api:

238 */

239 

240 

241 

242 

243 //****************************************************JSON

244 /**

245  系统自带的

246 */

247 /**

248  - (IBAction)btnPressIOS5Json:(id)sender {

249  

250  NSError *error;

251  //加载一个NSURL对象

252  NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.weather.com.cn/data/101180601.html"]];

253  //将请求的url数据放到NSData对象中

254  NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

255  //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中

256  NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];

257  NSDictionary *weatherInfo = [weatherDic objectForKey:@"weatherinfo"];

258  txtView.text = [NSString stringWithFormat:@"今天是 %@  %@  %@  的天气状况是:%@  %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];

259  NSLog(@"weatherInfo字典里面的内容为--》%@", weatherDic );

260  }

261  */

262 

263 /**

264  TouchJson

265  */

266 /**

267  //使用TouchJson来解析北京的天气

268  - (IBAction)btnPressTouchJson:(id)sender {

269  //获取API接口

270  NSURL *url = [NSURL URLWithString:@"http://m.weather.com.cn/data/101010100.html"];

271  //定义一个NSError对象,用于捕获错误信息

272  NSError *error;

273  NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];

274  NSLog(@"jsonString--->%@",jsonString);

275  //将解析得到的内容存放字典中,编码格式为UTF8,防止取值的时候发生乱码

276  NSDictionary *rootDic = [[CJSONDeserializer deserializer] deserialize:[jsonString dataUsingEncoding:NSUTF8StringEncoding] error:&error];

277  //因为返回的Json文件有两层,去第二层内容放到字典中去

278  NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];

279  NSLog(@"weatherInfo--->%@",weatherInfo);

280  //取值打印

281  txtView.text = [NSString stringWithFormat:@"今天是 %@  %@  %@  的天气状况是:%@  %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];

282  

283  }

284  */

285 

286 /**

287   SBJson

288  */

289 /**

290  //使用SBJson解析南阳的天气

291  - (IBAction)btnPressSBJson:(id)sender {

292  NSURL *url = [NSURL URLWithString:@"http://m.weather.com.cn/data/101180701.html"];

293  NSError *error = nil;

294  NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];

295  SBJsonParser *parser = [[SBJsonParser alloc] init];

296  

297  NSDictionary *rootDic = [parser objectWithString:jsonString error:&error];

298  NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];

299  txtView.text = [NSString stringWithFormat:@"今天是 %@  %@  %@  的天气状况是:%@  %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];

300  }

301  */

302 

303 /**

304   JSONKit

305  */

306 /**

307  - (IBAction)btnPressJsonKit:(id)sender {

308  

309  //如果json是“单层”的,即value都是字符串、数字,可以使用objectFromJSONString

310  NSString *json1 = @"{\"a\":123, \"b\":\"abc\"}";

311  NSLog(@"json1:%@",json1);

312  NSDictionary *data1 = [json1 objectFromJSONString];

313  NSLog(@"json1.a:%@",[data1 objectForKey:@"a"]);

314  NSLog(@"json1.b:%@",[data1 objectForKey:@"b"]);

315  [json1 release];

316  

317  //如果json有嵌套,即value里有array、object,如果再使用objectFromJSONString,程序可能会报错(测试结果表明:使用由网络或得到的php/json_encode生成的json时会报错,但使用NSString定义的json字符串时,解析成功),最好使用objectFromJSONStringWithParseOptions:

318  NSString *json2 = @"{\"a\":123, \"b\":\"abc\", \"c\":[456, \"hello\"], \"d\":{\"name\":\"张三\", \"age\":\"32\"}}";

319  NSLog(@"json2:%@", json2);

320  NSDictionary *data2 = [json2 objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];

321  NSLog(@"json2.c:%@", [data2 objectForKey:@"c"]);

322  NSLog(@"json2.d:%@", [data2 objectForKey:@"d"]);

323  [json2 release];

324  }

325  */

 

 

 

 

 

你可能感兴趣的:(ios开发)