0

i need to display a Table View containing information from web service response i do no where iam doing wrong here my sample code

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

    }

i need to parse 4 values from plan_history like "rate","description","validity","plan type" when i run my app i getting only one set of value in Table view . i.e my json string contains more than 20 records containing rate,description,validity and plan type
can u show me how to loop my json value and display all my records in Table View

4
  • Here in loop, you are re-writing the value each time the loop executes. And you will get only the last value. Either make rateString, descriptionString etc as NSMutableArray(not recommended) or make a NSMutableArray of dictionary or NSObject subclass that keeps an array of these values. Commented Jan 2, 2015 at 10:16
  • i cant get ur method,actually i parsed my value directly from webservices call. my values are printing good in Nslog but i dono to show my values in table view can u update some codes ? Commented Jan 2, 2015 at 10:23
  • @Harrypotter - you can create a class and take an array in appDelegate that will contain objects of that class. This way you can get all the records. Please check my answer below. Commented Jan 2, 2015 at 10:31
  • @Harrypotter are you still facing problem.... Commented Jan 2, 2015 at 10:39

4 Answers 4

1

You should eliminate those calls to allValues and valueForKey, as repeatedly calling those methods is very inefficient ways to tackle JSON parsing.

In one of your comments, you said that your JSON looked like:

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

(I wonder if there was something before this plan_history entry given your allValues reference, but unless you tell us otherwise, I'll assume this is what the original JSON looked like.)

If so, to parse it you would do:

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.

Where, PlanHistoryEntry might be defined like so:

@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

But I don't want you to get lost in the minutiae of this answer (because given the ambiguity of the question, I may have gotten some details wrong). The key point is that you should not be using allValues or valueForKey. Just navigate the JSON structure more directly as illustrated above.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this,

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

and use rateArray, descriptionArray etc.

2 Comments

will it return all values from array ?
As per your code, objectForKey:@"rate" and other key are array's. So you can use those arrays directly. If you can provide the json model, it will be more clear.
0

You can create a class storing your data as follows:

Something like:

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

Now in your .m file where you want to parse the data you can do something like:

    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

You can now access the arrayPlan declared in appDelegate as follows:

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

Hope this helps.

2 Comments

can u explain how u got arrayPlan its bit confusing bro
you will have to declare it in your appDelegate. Instead of declaring separate NSString variables just declare NSMutableArray *arrayPlan; in appDel. Hope you got it.
0

you need to store that value in fatalist control means in NSMutable array like this.

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

Now use

arrayHistory

to load data in table view

5 Comments

thanx for ur time bro, but still iam getting oly one records in all tablevie cell :(
now you have to use arrayHistry for putting data in Tableview. Please post your Tablevierw code so I will Explain you.
my json value is:"plan_history":[{"rate":"\u20b9 1000","description":"Full Talktime Topup Rs.1000 Full Talktime","validity":"Validity : 0\r","plantype":"Full TalkTime"},{"rate":"\u20b9 508","description":"Full Talktime Topup Rs.558 more than Full Talktime","validity":"Validity : 2\r","plantype":"Full TalkTime"} here u can find that what i am expecting is
first i should identify the array count then i should display total number of records in table view thats it
wats your array name? which was you used for displaying data in table view.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.