如何从字符串中的json获取数组响应?

时间:2015-09-01 08:28:44

标签: ios arrays json dictionary

我正在接受json的回复

 parcel =     (
                {
            datetime = "2015-08-31 21:48:45";
            height = 2;
            id = 21;
            invoice = NO;
            length = 2;
            mtype = IN;
            "num_item" = 2;
            "parcel_number" = 1;
            pname = "Parcel number - 1";
            "pro_number" = tanu;
            status = 1;
            type = Exact;
            uid = 185;
            weight = 2;
            width = 2;
            wtype = KG;
        }
    );

我想在字符串中获取高度,日期时间,发票。如何做到这一点? AnyOne可以帮助我......

4 个答案:

答案 0 :(得分:3)

NSArray * arr_Parcel = [[NSArray alloc]initWithArray:data];
NSMutableDictionary * temp_Dict = [[NSMutableDictionary alloc]init];
for (int i = 0 ; i < arr_Parcel.count; i++)
    {
        temp_Dict = [arr_Parcel objectAtIndex:i];
         NSString * strHeight = [temp_Dict objectForKey:"height"];
         NSString * strdate = [temp_Dict objectForKey:"datetime"];


     }

答案 1 :(得分:1)

如果您使用的是Swift,请使用SwiftJSON来使用JSON。 它易于使用。例如:

var jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let json = JSON(data: jsonData)
print(json["height"].double) // 2
print(json["datatime"].string) // "2015-08-31 21:48:45"
...

答案 2 :(得分:1)

创建一个NSObject类并传递NSDictionary制作模型类。

In your ViewController Class:

&#34;包裹&#34;是你的数组

ModelClass * modelClass = [ModelClass alloc] initWithNewsDictionary: parcel[0]];

ModelClass.h Class中创建所需的变量。

-(id)initWithNewsDictionary:(NSDictionary *)dictionary
{
    self = [super init];
    if (self) {
        self.height     = dictionary[@"height"];
        self.datetime   = dictionary[@"datetime"];
        self.invoice    = dictionary[@"invoice"];
        self.weight     = dictionary[@"weight"];
    }
    return self;
}

答案 3 :(得分:0)

试试这个: -

   NSString *height=[NSString stringWithFormat:@"%@",[[[YourJson valueForKey:@"parcel"] objectAtIndex:0] objectForKey:@"height"]];
   NSString *dateTime=[NSString stringWithFormat:@"%@",[[[YourJson valueForKey:@"parcel"] objectAtIndex:0] objectForKey:@"datetime"]];
   NSString *invoice=[NSString stringWithFormat:@"%@",[[[YourJson valueForKey:@"parcel"] objectAtIndex:0] objectForKey:@"invoice"]];
   NSLog(@"height : %@ , date=%@ ,invoice=%@",height,dateTime,invoice);
相关问题