How to store values of JSON in ARRAY/ String - iphone

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

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
)

Refere
http://www.xprogress.com/post-44-how-to-parse-json-files-on-iphone-in-objective-c-into-nsarray-and-nsdictionary/
http://mobileorchard.com/tutorial-json-over-http-on-the-iphone/
http://mobile.tutsplus.com/tutorials/iphone/iphone-json-twitter-api/
http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c

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

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

Related

Array not get data for particular key

Response array like this
NewDataSet = {
Table = (
{
City = {
text = "\nThiruvananthapuram";
};
Country = {
text = "\n\nIndia";
};
text = "\n";
},
{
City = {
text = "\nVellore";
};
Country = {
text = "\n\nIndia";
};
text = "\n";
}
);
text = "\n";
I have write this code..
xmlDictionary = [XMLReader dictionaryForXMLString:xmlResultString error:nil];
NSLog(#"%#",xmlDictionary);
NSLog(#"%#",xmlDictionary);
NSArray * responseArr = xmlDictionary[#"NewDataSet"];
NSLog(#"%#",responseArr);
for(NSDictionary * dic in responseArr)
{
NSLog(#"%#",dic);
//[array1 addObject:[dic valueForKey:#"City"]];
[array1 addObject:[[dic valueForKey:#"City"] valueForKey:#"text"]];
}
but not get the data. in array1. please help me out this thanks in advance.
Problem is i will not get the value in NSDictionary.
Error log is
this class is not key value coding-compliant for the key City.'
I got my Solution problem is i will not get the direct City key. Because City key is under the NewDataSet & Table
so first you go to the NewDataSet and then Table key then finally you get the City key.
Now get array data from Dictionary Like
NSArray * City=[[NSArray alloc]init];
City=[[[xmlDictionary valueForKey:#"NewDataSet"] valueForKey:#"Table"] valueForKey:#"City"];
NSLog(#"%#",City);
pass multiple keys inside key this is the solution.
It seems you haven't allocated array1 anywhere,
Your solution goes here:
array1 = [[NSMutableArray alloc]init];
for(NSDictionary * dic in responseArr)
{
[array1 addObject:[dic valueForKey:#"City"]];
}
NSLog(#"array1 >> %#",array1);
If you have already allocated array1, then please try to log the value for [dic valueForKey:#"City"].
try this code...
for(int i =0;i<[responseArr count];i++)
{
NSString *str = [[responseArr objectAtIndex:i] valueForKey:#"City"];
[array1 addObject:str];
}
let me know it is working or not!!!
Happy Coding!!!
array1 = [[NSMutableArray alloc]init];
for(NSDictionary * dic in responseArr)
{
[array1 addObject:[dic objectForKey:#"City"]];
}
NSLog(#"array1 >> %#",array1);
Try this

Dictionary Value retrieve

In my application ,the dictionary value contains following content.How to retrieve the each and store it new array
contryArray(
{
checka0 = Thailand;
checka1 = Brazil;
checka10 = Marocco;
checka11 = Thailand;
checka12 = Jordan;
checka13 = Colombia;
checka14 = Kuwait;
checka3 = Mexico;
checka4 = "Saoudi Arabia";
checka5 = Chili;
checka7 = Australia;
checka8 = Malta;
checka9 = "South Africa";
checkb0 = havana;
checkb1 = Santos;
checkb10 = Casablanca;
checkb11 = Bangkok;
checkb12 = Aqaba;
checkb13 = Havana;
checkb14 = Shuwaikh;
checkb3 = Veracruz;
checkb4 = Jeddah;
checkb5 = "San Antonio";
checkb7 = Maersk;
checkb8 = Maraxklokk;
checkb9 = Durban;
checkc0 = 1;
checkc1 = "0.7";
checkc10 = 1;
checkc11 = "1.2";
checkc12 = 1;
checkc13 = "1.4";
checkc14 = 1;
checkc3 = "0.9";
checkc4 = "0.8";
checkc5 = "0.9";
checkc7 = "2.7";
checkc8 = "0.8";
checkc9 = "0.9";
}
For ex: checka0-checka14 in one array, Here the problem is checka2 and checka6 is not available, Im new bee in xcode,Please help me to retrieve
Your question is not clear. Possibly you need to get all keys in your dictionary and separating each item with specific word in it(checka/checkb/checkc).
If that is the case then,
You will get all the keys using:
NSArray *dictKeys = [yourDictionary allKeys];
You can implement this in multiple ways, one of them:
For storing it in same array:
for (NSString *key in [yourDictionary allKeys])
{
[yourArray addObject:[yourDictionary objectForKey:key]];
}
For storing it in seperate arrays:
for (NSString *key in [yourDictionary allKeys])
{
if([key rangeOfString:#"checka"].location != NSNotFound)
{
//add checka to first array
[yourFirstArray addObject:[yourDictionary objectForKey:key]];
}
else if([key rangeOfString:#"checkb"].location != NSNotFound)
{
//add checkb to second array
[yourSecondArray addObject:[yourDictionary objectForKey:key]];
}
...
}
if contryArray is your dictionary then access it as follow
[contryArray valueForKey:#"checka0"];
and go on adding this values to another array
You can use the following code:
- (void)filterDictionary:(NSDictionary *)dict
{
NSArray *allKeys = [dict allKeys];
NSMutableArray *allValues = [[NSMutableArray alloc]init];
for(id key in allKeys)
{
id value = [dict valueForKey:key];
[allValues addObject:[value stringValue]];
}
}

Getting Array with values from an array of NSDictionary

I have an array with 4 Dictionaries with key #"preference" like as follows
(
{
preference = Nose;
},
{
preference = "Heart rate";
},
{
preference = Glucose;
},
{
preference = Food;
}
)
Now i want to retrieve an array for these dictionary values like"
(
Nose, Heart rate, Glucose, Food
)
How s'd i get it.. Thanks in advance
A one-liner:
NSArray *resultingArray = [arrayOfDictionaries valueForKeyPath:#"preference"];
Try it:
NSArray *result = [dictionaryObject valueForKeyPath:#"preference"];
It'll solve your Problem
Do something like this:
NSMutableArray *collectedValues = [NSMutableArray arrayWithCapacity:array.count];
for (NSDictionary *dict in array) {
NSString *value = [dict objectForKey:#"preference"];
if (value) {
[collectedValues addObject:value];
}
}
Try with this code:
myArray is your first array
mySecondArray is the array you have in the end
NSMutableArray *mySecondArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [myArray count] ; i++)
{
NSDictionary *tempDict = [myArray objectForIndex:i];
[mySecondArray addObject:[tempDict objectForKey#"preference"]];
}

How to get values from unknown key in NSDictionary iphone?

I have one more big problem while parse the values from Webservice response. I dont know the key for the values in the webservice response. For example,
class = (
{
"ObjectiveC" =
(
{
"brief_desc" = "ObjectiveC";
date = "2008-02-27";
"event_status" = Attended;
},
{
"brief_desc" = "ObjectiveC";
date = "2008-03-05";
"event_status" = Attended;
},
{
"brief_desc" = "ObjectiveC";
date = "2008-03-12";
"event_status" = Missed;
},
);
},
{
"Java" = (
{
"brief_desc" = "Java";
date = "2008-02-27";
"event_status" = Attended;
},
{
"brief_desc" = "Java";
date = "2008-03-05";
"event_status" = Attended;
},
{
"brief_desc" = "Java";
date = "2008-03-12";
"event_status" = Missed;
},
);
}
);
In this response even we dont know the keys "ObjectiveC" and "Java". The keys("ObjectiveC and Java") should be change in every response retured. How to get values of key (Unknown key)? How can i parse this response and get the values?
I would enumerate through the keys to get the value. Here is an example of enumeration in objective-c.
NSEnumerator *enumerator = [myDictionary keyEnumerator];
id key;
while ((key = [enumerator nextObject])) {
//assuming value will be string
NSString *valueForKey = [myDictionary valueForKey:key];
//assuming value is another dictionary
NSDictionary *subDictionary = [myDictionary objectForKey:key];
}
And if you don't know the keys of the sub dictionaries, you can enumerate through those as well.
NSDictionary has - (NSArray *)allKeys and - (NSArray *)allValues. One of those might help
NSDictionary * lessonDict = [[NSDictionary alloc] initWithObjectsAndKeys:#"Key", #"Value", #"Key 2", #"Value 2", nil];
NSArray *values = [lessonDict allValues];
NSArray *keys = [lessonDict allKeys];
NSLog(#"Keys: %#",keys);
NSLog(#"Values: %#",values);

Loop through NSDictionary to create separate NSArrays

I have a large NSDictionary that I need to loop through and create separate NSArrays. Here are the contents:
(
{
id = {
text = "";
};
sub = {
text = " , ";
};
text = "";
"thumb_url" = {
text = "";
};
title = {
text = "2010-2011";
};
type = {
text = "title";
};
},
{
id = {
text = "76773";
};
sub = {
text = "December 13, 2010";
};
text = "";
"thumb_url" = {
text = "http://www.puc.edu/__data/assets/image/0004/76774/varieties/thumb.jpg";
};
title = {
text = "College Days - Fall 2010";
};
type = {
text = "gallery";
};
},
{
id = {
text = "";
};
sub = {
text = "";
};
text = "";
"thumb_url" = {
text = "";
};
title = {
text = "2009-2010";
};
type = {
text = "title";
};
},
{
id = {
text = "76302";
};
sub = {
text = "December 3, 2010";
};
text = "";
"thumb_url" = {
text = "http://www.puc.edu/__data/assets/image/0019/76303/varieties/thumb.jpg";
};
title = {
text = "Christmas Colloquy";
};
type = {
text = "gallery";
};
}
)
Each section has a type key, which I need to check. When it finds the title key, I need to add those to an array. Then the next sections that would use the gallery key needs to be in its own array until it finds another title key. Then the gallery keys after that into their own array.
I am using a UITableView section titles and content. So, the NSDictionary above should have one NSArray *titles; array, and two other arrays each containing the galleries that came after the title.
I have tried using a for loop but I just can't seem to get it right. Any ideas would be appreciated.
It's somewhat unclear by your log, but I'm guessing your NSDictionary has values of NSDictionary? If so:
NSMutableArray *titles = [NSMutableArray array];
// etc.
for (id key in sourceDictionary) {
NSDictionary *subDictionary = [sourceDictionary objectForKey:key];
if ([subDictionary objectForKey:#"type"] == #"title")
[titles addObject:[subDictionary objectForKey:#"title"]];
// etc.
}
Your question is a bit unclear... but this is how you would properly loop through an NSDictionary.
EDIT:
NSMutableDictionary *galleries = [NSMutableDictionary dictionary];
NSString *currentTitle;
for (id key in sourceDictionary) {
NSDictionary *subDictionary = [sourceDictionary objectForKey:key];
NSString *type = [subDictionary objectForKey:#"type"];
if (type == #"title") {
currentTitle = [subDictionary objectForKey:#"title"];
if ([galleries objectForKey:currentTitle] == nil)
[galleries setObject:[NSMutableArray array] forKey:currentTitle];
} else if (type == #"gallery" && currentTitle != nil)
[[galleries objectForKey:currentTitle] addObject:subDictionary];
}
After this loop, galleries will contain keys of type NSString (with values of the titles), and corresponding objects of type NSArray (with values of the gallery NSDictionarys). Hopefully this is what you were going for.
NSString *key;
for(key in someDictionary){
NSLog(#"Key: %#, Value %#", key, [someDictionary objectForKey: key]);
}
Modern Objective-C syntax:
NSMutableArray *things = [NSMutableArray array];
NSMutableArray *stuff = [NSMutableArray array];
NSMutableArray *bits = [NSMutableArray array];
[dictionaries enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[things addObject:[obj valueForKeyPath:#"thing"]];
[stuff addObject:[obj valueForKeyPath:#"enclosing_object.stuff"]];
[bits addObject:[obj valueForKeyPath:#"bits"]];
}];