简体   繁体   English

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

[英]how to get array response from json in string?

I am getting the response from json like this我从这样的 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;
        }
    );

I want to get the height,date time,invoice in a string.. How can this be done?我想获取字符串中的高度、日期时间、发票.. 怎么做? AnyOne can help me for this...任何人都可以帮助我解决这个问题...

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"];


     }

If you are using Swift, use SwiftJSON to work with JSON.如果您使用 Swift,请使用SwiftJSON来处理 JSON。 It's easy to use.它很容易使用。 For example:例如:

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"
...

Create a NSObject Class and pass the NSDictionary the make a model class.创建一个NSObject类并通过NSDictionary创建一个模型类。

In your ViewController Class:

" parcel" is your Array “包裹”是你的阵列

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

Create needed variables in ModelClass.h Class.ModelClass.h类中创建所需的变量。

-(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;
}

Try this :-尝试这个 :-

   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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM