标签:
//
// ViewController.m
// JSON序列化2
//
// Created by 潘荟 on 16/6/20.
// Copyright © 2016年 BAT. All rights reserved.
//
#import "ViewController.h"
#import "OnePiece.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//1.字符串
// NSString *str = @"{\"name\":\"luffy\",\"age\":\"18\"}";
// NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
//2.字典
// NSDictionary *dic = @{@"name":@"sabo",@"age":@"19"};
// NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:0 error:NULL];
//3.数组
// NSArray *array = @[
// @{@"name":@"sanji"},
// @{@"age":@"23"}
// ];
// NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];
//4.自定义对象
// OnePiece *op = [[OnePiece alloc] init];
// op.name = @"luffy";
// op.age = 23;
// [op setValue:@(0) forKey:@"is_D"];
//
// if (![NSJSONSerialization isValidJSONObject:op]) {
// NSDictionary *dic = [op dictionaryWithValuesForKeys:@[@"name",@"age"]];
//
// NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:0 error:NULL];
//
// [self getJson:data];
//
// }else {
// NSLog(@"不符合");
// }
//5.自定义多个对象
OnePiece *op1 = [[OnePiece alloc] init];
op1.name = @"nami";
op1.age = 18;
[op1 setValue:@(0) forKey:@"is_D"];
OnePiece *op2 = [[OnePiece alloc] init];
op2.name = @"luffy";
op2.age = 22;
[op2 setValue:@(1) forKey:@"is_D"];
NSArray *array = @[op1,op2];
NSMutableArray *marr = [NSMutableArray array];
[array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSDictionary *dic = [obj dictionaryWithValuesForKeys:@[@"name",@"age",@"is_D"]];
[marr addObject:dic];
}];
NSData *data = [NSJSONSerialization dataWithJSONObject:marr options:0 error:NULL];
[self getJson:data];
}
- (void)getJson:(NSData *)data {
NSURL *url = [NSURL URLWithString:@"http://192.168.29.103/php/upload/postjson.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = data;
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError) {
NSLog(@"conn error");
return;
}
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200 || httpResponse.statusCode == 304) {
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",string);
}else {
NSLog(@"server error");
}
}];
}
@end
标签:
原文地址:http://www.cnblogs.com/panhui/p/5601676.html