JSON解析例子

时间:2023-03-09 19:32:26
JSON解析例子

//解析的东西是数组就用数组接受,是字典就用字典接受

//my.h
#ifndef __1_Header_h
#define __1_Header_h
#define DEBUG 1
#define aa 1

#ifdef aa
#ifdef DEBUG
#define NSLog(FORMAT, ...) fprintf(stderr,"%s\n",[[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
#define NSLog(...)
#endif
#endif

#ifdef bb
#ifdef DEBUG
#define NSLog(FORMAT, ...) fprintf(stderr,"%s:%d\t%s\n",[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
#define NSLog(...)
#endif
#endif

#endif
//main.c

#import <Foundation/Foundation.h>
#import "Users.h"
#import "my.h"
#define PATH2 @"http://10.0.8.8/sns/my/user_list.php?number=20&page=1"
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        //创建一个URL
        NSURL *url = [NSURL URLWithString:PATH2];
        //发送请求来获得返回的JSON数据
        NSData *data = [[NSData alloc] initWithContentsOfURL:url];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:1 error:nil];
        NSArray *array = [dic objectForKey:@"users"];
        NSMutableArray *marray = [NSMutableArray new];
        for(id obj in array)
        {
            NSLog(@"username:%@,credit:%@",obj[@"username"],obj[@"credit"]);
            Users *users = [Users new];
            users.name = obj[@"username"];
            users.cre = obj[@"credit"];
            [marray addObject:users];
        }
        for(Users *user in marray)
        {
            NSLog(@"uid:%@,username:%@",user.name,user.cre);
        }
   }
    return 0;
}
//Users.h

//
//  Users.h
//  Json
//
//  Created by hehe on 15/9/8.
//  Copyright (c) 2015年 wang.hehe. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Users : NSObject
@property (nonatomic,strong)NSString * name;
@property (nonatomic,strong)NSString *cre;
@end
//Users.m

//
//  Users.m
//  Json
//
//  Created by hehe on 15/9/8.
//  Copyright (c) 2015年 wang.hehe. All rights reserved.
//

#import "Users.h"

@implementation Users

@end