V.V
V.V

Reputation: 3094

How to store values of JSON in ARRAY/ String

I have the following JSON value:

-(
            { Key   = IsEmail;
              Value = 1;     },

            { Key   = TrackingInterval;
              Value = 20;    },

            { Key   = IsBackup;
              Value = 1;     },

            { Key   = WipeOnRestore;
              Value = 1;     }
)

How might I go about parsing this object into an array or string? - i.e. eack key values to be stored in an array and each Value to be stored in another array.

Please help me out with this.

Thanks :)

Upvotes: 0

Views: 2374

Answers (4)

SriPriya
SriPriya

Reputation: 1240

if the JSON is in below format,

responseString=[ {
        Key = IsEmail;
        Value = 1;
    },
            {
        Key = TrackingInterval;
        Value = 20;
    },
            {
        Key = IsBackup;
        Value = 1;
    },
            {
        Key = WipeOnRestore;
        Value = 1;
    }] 

 then,

NSArray *resultArray=[responseSrting JSONValue];

NSMuatbleArray *keyArray=[[NSMutableArray alloc] init];

NSMutableArray *valueArray=[[NSMutableArray alloc] init];

for(NSDictionary *dict in resultsArray){

[keyArray addObject:[dict objectForKey:@"Key"]];

[valueArray addObject:[dict objectForKey:@"Value"]];

}

then, all your keys are stored in keyArray and all your values are stored in valueArray

Upvotes: 0

Nick Weaver
Nick Weaver

Reputation: 47241

This approach uses the json-framework.

I've shortened your example:

NSString *jsonString = @"[{\"Key\":\"IsEmail\",\"Value\":\"1\"},{\"Key\":\"TrackingInterval\",\"Value\":\"20\"},{\"Key\":\"IsBackup\",\"Value\":\"1\"}]";

NSMutableArray *keys = [NSMutableArray array];
NSMutableArray *values = [NSMutableArray array];    

NSArray *json = [jsonString JSONValue];

for (NSDictionary *pair in json) {
    [keys addObject:[pair objectForKey:@"Key"]];
    [values addObject:[pair objectForKey:@"Value"]];        
}

NSLog(@"%@", keys); 
NSLog(@"%@", values);

Output:

2011-05-18 14:23:55.698 [36736:207] (
    IsEmail,
    TrackingInterval,
    IsBackup
)
2011-05-18 14:23:55.700 [36736:207] (
    1,
    20,
    1
)

Upvotes: 5

Mike C
Mike C

Reputation: 3117

Your data is not vald json, You may want to structure it more like this:

var theObj = { IsEmail: 1, TrackingInterval: 20, IsBackup: 1, WipeOnRestore: 1 };

Then you could populate your key and value arrays something like this:

var keys = new Array();
var values = new Array();

for (prop in theObj) {
    keys.push(prop);
    values.push(theObj[prop]);
}

Upvotes: 0

Related Questions