为数组创建循环以从json String获取字符串?

时间:2015-01-02 10:14:07

标签: ios iphone json nsdictionary

我需要显示一个包含来自Web服务响应的信息的表视图我不知道我在哪里做错了我的示例代码

    NSData *data = [soapResultsString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    NSArray *array = [json allValues];

    for (int i=0; i<array.count; i++)
    {
        recordResults =NO;
        appDelegate.rateString  =[[[json valueForKey:@"plan_history"]valueForKey:@"rate"]objectAtIndex:i];
        appDelegate.descriptionString=[[[json valueForKey:@"plan_history"]valueForKey:@"description"]objectAtIndex:i];
        appDelegate.validityString=[[[json valueForKey:@"plan_history"]valueForKey:@"validity"]objectAtIndex:i];
        appDelegate.plantypeString=[[[json valueForKey:@"plan_history"]valueForKey:@"plantype"]objectAtIndex:i];

    }

我需要解析来自plan_history的4个值,如&#34; rate&#34;,&#34; description&#34;,&#34; validity&#34;,&#34; plan type&#34; 当我运行我的应用程序时,我只在表视图中获得一组值。即我的json字符串包含20多条包含费率,描述,有效性和计划类型的记录 你能告诉我如何循环我的json值并在Table View中显示我的所有记录

4 个答案:

答案 0 :(得分:1)

您应该取消对allValuesvalueForKey的调用,因为重复调用这些方法是解决JSON解析的非常低效的方法。

在你的一条评论中,你说你的JSON看起来像是:

{
    "plan_history": [
        {
            "rate": "₹1000",
            "description": "FullTalktimeTopupRs.1000FullTalktime",
            "validity": "Validity: 0\r",
            "plantype": "FullTalkTime"
        },
        {
            "rate": "₹508",
            "description": "FullTalktimeTopupRs.558morethanFullTalktime",
            "validity": "Validity: 2\r",
            "plantype": "FullTalkTime"
        }
    ]
}

(我想知道在给出plan_history引用的allValues条目之前是否有某些内容,但除非您另有说明,否则我将假设这是原始JSON的样子。)

如果是这样,要解析它你会这样做:

NSMutableArray *results = [NSMutableArray array];

NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSArray *planHistory = json[@"plan_history"];

for (NSDictionary *planHistoryEntry in planHistory) {
    NSString *rateString  = planHistoryEntry[@"rate"];
    NSString *description = planHistoryEntry[@"description"];
    NSString *validity    = planHistoryEntry[@"validity"];
    NSString *planType    = planHistoryEntry[@"plantype"];

    // now do whatever you want with these four values.

    // for example, I'd generally create a custom object I defined elsewhere for these four values and add to results, e.g.

    [results addObject:[PlanHistoryEntry planHistoryEntryWithRate:rateString
                                                      description:description
                                                         validity:validity
                                                         planType:planType]];
}

// now do something with results, e.g. store it in some property in `appDelegate`, etc.

其中,PlanHistoryEntry可能如此定义:

@interface PlanHistoryEntry : NSObject

@property (nonatomic, copy) NSString *rateString;
@property (nonatomic, copy) NSString *planDescription;  // note, do not use `description` for property name
@property (nonatomic, copy) NSString *validity;
@property (nonatomic, copy) NSString *planType;

+ (instancetype) planHistoryEntryWithRate:(NSString *)rateString
                          planDescription:(NSString *)planDescription
                                 validity:(NSString *)validity
                                 planType:(NSString *)planType;

@end

@implementation PlanHistoryEntry

+ (instancetype) planHistoryEntryWithRate:(NSString *)rateString
                          planDescription:(NSString *)planDescription
                                 validity:(NSString *)validity
                                 planType:(NSString *)planType
{
    PlanHistoryEntry *entry = [[self alloc] init];
    entry.rateString = rateString;
    entry.planDescription = planDescription;
    entry.validity = validity;
    entry.planType = planType;

    return entry;
}

@end

但是我不希望你迷失在这个答案的细枝末节中(因为考虑到问题的模糊性,我可能会得到一些错误的细节)。关键是您不应该使用allValuesvalueForKey。只需更直接地导航JSON结构,如上所示。

答案 1 :(得分:0)

试试这个,

NSData *data = [soapResultsString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

NSArray *rateArray = [[json objectForKey:@"plan_history"] objectForKey:@"rate"];
NSArray * descriptionArray = [[json objectForKey:@"plan_history"] objectForKey:@"description"];
NSArray * validityArray = [[json objectForKey:@"plan_history"] objectForKey:@"validity"];
NSArray * plantypeArray = [[json objectForKey:@"plan_history"] objectForKey:@"plantype"];

并使用rateArraydescriptionArray

答案 2 :(得分:0)

您可以创建一个存储数据的类,如下所示:

类似的东西:

planClass.h
@property(nonatomic, strong) NSString * rateString;
@property(nonatomic, strong) NSString * descriptionString;
@property(nonatomic, strong) NSString * validityString;
@property(nonatomic, strong) NSString * plantypeString;

plan.m
//@synthesize the properties of .h

现在,在您要解析数据的.m文件中,您可以执行以下操作:

    NSData *data = [soapResultsString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    NSArray *array = [json allValues];

    for (int i=0; i<array.count; i++)
    {
planClass *pc = [[planClass alloc]init];
        recordResults =NO;
        pc.rateString  =[[[json valueForKey:@"plan_history"]valueForKey:@"rate"]objectAtIndex:i];
        pc.descriptionString=[[[json valueForKey:@"plan_history"]valueForKey:@"description"]objectAtIndex:i];
        pc.validityString=[[[json valueForKey:@"plan_history"]valueForKey:@"validity"]objectAtIndex:i];
        pc.plantypeString=[[[json valueForKey:@"plan_history"]valueForKey:@"plantype"]objectAtIndex:i];
    [appDelegate.arrayPlan addObject:pc];
    }
NSLog(@"appDelegate.arrayPlan >> %@",appDelegate.arrayPlan); // you'll get array of planClass objects

您现在可以访问arrayPlan中声明的appDelegate,如下所示:

for(id *obj in arrayPlan)
{
    planClass *pc = (planClass *)obj;
    NSLog("rate: %@",[pc valueForKey:@"rateString"]);
    NSLog("descriptionString: %@",[pc valueForKey:@"descriptionString"]);
    NSLog("validityString: %@",[pc valueForKey:@"validityString"]);
    NSLog("plantypeString: %@",[pc valueForKey:@"plantypeString"]);
}

希望这有帮助。

答案 3 :(得分:0)

你需要将这个值存储在NSMutable数组中的宿命控制手段中。

 NSData *data = [soapResultsString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSMutableArray *arrayHistory = [[NSMutableArray alloc]init];

    NSArray *array = [json allValues];

    for (int i=0; i<array.count; i++)
    {
        recordResults =NO;
        appDelegate.rateString  =[[[json valueForKey:@"plan_history"]valueForKey:@"rate"]objectAtIndex:i];
        appDelegate.descriptionString=[[[json valueForKey:@"plan_history"]valueForKey:@"description"]objectAtIndex:i];
        appDelegate.validityString=[[[json valueForKey:@"plan_history"]valueForKey:@"validity"]objectAtIndex:i];
        appDelegate.plantypeString=[[[json valueForKey:@"plan_history"]valueForKey:@"plantype"]objectAtIndex:i];

            [arrayHistory addObject:appDelegate.rateString];
            [arrayHistory addObject:appDelegate.descriptionString];
            [arrayHistory addObject:appDelegate.validityString];
            [arrayHistory addObject:appDelegate.plantypeString];
    }

现在使用

  

arrayHistory

在表格视图中加载数据