zoukankan      html  css  js  c++  java
  • 处理JSON格式的数据

      JSON格式的数据是最常用的数据格式,处理方法的选择就显得比较重要了。我常用的一种是用对象来接收,然后保存在数组中,需要时直接从数组中取值。下面列出一个小例子。

      1、在.h文件中:

    #import <Foundation/Foundation.h>

    @interface DailyWeathers : NSObject

    @property(nonatomic,strong) NSString *date;

    @property(nonatomic,strong) NSString *maxtempF;

    @property(nonatomic,strong) NSString *mintempF;

    @property(nonatomic,strong) NSURL *weatherIconUrl;

    +(id)weatherWithJSON:(NSDictionary*)json;

    @end

      2、在.m文件中:

    #import "DailyWeathers.h"

    @implementation DailyWeathers

    +(id)weatherWithJSON:(NSDictionary *)json{

        return [[self alloc] initWithJSON:json];

    }

    -(id)initWithJSON:(NSDictionary*)json{

        self = [super init];

        if (self) {

            self.date = json[@"date"];

            self.maxtempF = json[@"maxtempF"];

            self.mintempF = json[@"mintempF"];

            self.weatherIconUrl = [NSURL URLWithString:json[@"hourly"][3][@"weatherIconUrl"][0][@"value"]];

        }

        return self;

    }

    @end

      3、在网络请求数据的地方,直接调用下面的方法:

    -(NSArray*)dailyWeathersWithKeyFromJSON:(id)json{

        NSMutableArray *result = [NSMutableArray new];

        NSArray *weathers = json[@"data"][@"weather"];

        for (NSDictionary *weather in weathers) {

            DailyWeathers *dailyWeather = [DailyWeathers weatherWithJSON:weather];

            [result addObject:dailyWeather];

        }

        return [result copy];

    }

      

  • 相关阅读:
    pip 使用代理
    npm i -S -D -g 区别
    javascript JSON. 转换 注意事项
    hexo 博客
    kotlin 注意的地方
    VMware-workstation-full-10.0.1-1379776 CN
    分析公司shareaholic报告:Chrome浏览器使用量居首
    搜狗高速浏览器4.2正式版发布
    中行用户购买KIS2014 68元/3年,时间:2013.10.18-2013.11.18
    1元抢卡巴KAV_不限量疯抢即日起至2013.10.31截止
  • 原文地址:https://www.cnblogs.com/yyt-hehe-yyt/p/4717211.html
Copyright © 2011-2022 走看看