Fetch JSON Response Into Propertylist For UITableview - ios

I am trying to store JSON response Into propertylist like below Image of plist structured.
My Response:
{
"response": {
"count": "1000",
"girls": {},
"boys": {
"0": {
"name": "sam"
},
"1": {
"name": "jhon"
},
"2": {
"name": "keen"
},
"3": {
"name": "man"
},
"4": {
"name": "blue"
}
}
}
}
Need to Achieve :
FYI: After stored all the Information's I need to get Girls array data and Boys array data based on segment button selection It should reload the data quickly on tableview.
Needed Help :
How to fetch all the JSON data like my posted Image plist structure?
How to get and load It Into UItableview NSMutableArray?

First step:
Convert JSON string to dictionary
NSError *jsonError;
NSData *objectData = [strJSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
Second Step:
Make a dictionary for plist
NSMutableDictionary * tempDict = [[NSMutableDictionary alloc] init];
[tempDict setObject:[[json objectForKey:#"response"] objectForKey:#"girls"] forKey:#"girls"];
[tempDict setObject:[[json objectForKey:#"response"] objectForKey:#"boys"] forKey:#"boys"];
Last Step:
Write this dictionary to pList file
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:#"myPlistFile.plist"];
[tempDict writeToFile:plistPath atomically: YES];
EDIT : If you dont want to write this dict to plist file, ignore last step.
Just use your tempDict as tableView dataSource.
Number of sections : [[tempDict allKeys] count]
Number of rows in section :
if (indexPath.section == 0)
{
return [[tempDict objectForKey:#"girls"] allKeys];
}
else
{
return [[tempDict objectForKey:#"boys"] allKeys];
}
for cell configuration,
if (indexPath.section == 0)
{
lblTitle.text = [[[tempDict objectForKey:#"girls"] objectForKey:[NSString stringWithFormat:#"%d",indexPath.row] objectForKey:#"name"];
}
else
{
lblTitle.text = [[[tempDict objectForKey:#"boys"] objectForKey:[NSString stringWithFormat:#"%d",indexPath.row] objectForKey:#"name"];
}
Hope this will help you....

See the below worked out example
NSDictionary *dictionary = #{#"response": #{
#"count": #"1000",
#"girls": #{},
#"boys": #{
#"0": #{#"name": #"sam"},
#"1": #{#"name": #"jhon"},
#"2": #{#"name": #"keen"},
#"3": #{#"name": #"man"}
}
}
};
//return boys count while loading boys.
return [[[dictionary valueForKey:#"response"] valueForKey:#"boys"] allKeys].count;
//return girls count while loading boys.
return [[[dictionary valueForKey:#"response"] valueForKey:#"girls"] allKeys].count;
//Use this in cell for indexpath for row.
NSDictionary *boys = [[dictionary valueForKey:#"response"] valueForKey:#"boys"];
NSString *nameString = [[boys valueForKey:[NSString stringWithFormat:#"%ld",(long)indexPath.row]] valueForKey:#"name"];
//To get all name of boys at once
NSArray *boysName = [boys valueForKeyPath:#"name"];

Related

IOS how to replace json data using their keys

I want to change the following JSON.
My requirement is that I want to replace ("answer": "offlinetesing") with ("answer": "test12333") in a loop. Suppose if it is in index 0 I want to replace only for index 0 answer.
How can I achieve this?
I am using this code
NSData *data = [NSData dataWithContentsOfFile:documentFile1];
NSMutableDictionary *jsonObject1 = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSLog(#"jsonObject1 is %#",jsonObject1);
NSMutableArray *responsedictonary=[jsonObject1 objectForKey:#"questions"];
JSON:
{
"currentquestion": "Define6",
"phasecompletion": "80",
"questions": [
{
"answer": "offlinetesing",
"dmaicQuestion_ID": "Define1",
"projectPhase": "Define"
},
{
"answer": "testing",
"dmaicQuestion_ID": "Define2",
"projectPhase": "Define"
}
],
"questionsAnswered": 8
}
following answer would be helpful to you.
NSArray *questionArray = [jsonObject valueForKey#"questions"];
NSMutableArray *array = [NSMutableArray array];
for(NSDictionary *tempDict in questionArray){
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:[tempDicr mutablecopy];
NSString *str = [dict valueForKey:#"answer"];
if(str isEqualToString:#"offlinetesing"){
[dict setObject:#"test" forKey:#"answer"];
}
[array addObject:dict];
}

Get the values from JSON string using NSDictionary

How can i get values from the following JSON.
JSON
{
"X": [
{
"one": 1,
"two": "Bill"
},
{
"one": 2,
"two": "Hutch"
}
]
}
CODE
NSDictionary *dictionary = (NSDictionary *) responseObject;
dc =[dictionary objectForKey:#"X"];
Now how can i print the value of "one" and "two"
NB : dc is a NSMutableDictionary.
Use this code..
NSString *str = #"{\"X\":[{\"one\": 1, \"two\": \"Bill\" }, { \"one\": 2, \"two\": \"Hutch\" } ] }";
str = #"{\"X\":[{\"one\": 1,},{\"one\": 2,\"two\": \"Hutch\"}]}";
NSError *jsonError;
NSData *objectData = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(#"%#",[json objectForKey:#"X"]);
NSMutableDictionary *dict = [json objectForKey:#"X"];
for (NSDictionary *tempDict in dict) {
NSLog(#"%#",tempDict);
if ([tempDict objectForKey:#"one"]) {
NSLog(#"%#",[tempDict objectForKey:#"one"]);
}
if ([tempDict objectForKey:#"two"]){
NSLog(#"%#",[tempDict objectForKey:#"two"]);
}
}
Hope this helps you :)
See here is your JSON
{
"X": [
{
"one": 1,
"two": "Bill"
},
{
"one": 2,
"two": "Hutch"
}
] }
To get the second object from X array and in that value of "one" :
NSString *value = [[[dictionary objectForKey:#"X"] objectAtIndex: 1] objectForKey: #"one"];
Here is explanation into multiple line for the same code used above in single line:
NSArray *arr = [dictionary objectForKey:<Root Key String>]; // save data to array from dictionary
NSDictionary *dict = [arr objectAtIndex: <Index of object>]; // get the actual object from array based on index
NSString *resultString = [dict objectForKey: <Key String>]; // get value of your required key

Incorrectly parse json into NSDictionary

I am trying store text fields data into a NSDictionary from json. I have used SBJson for this.
{
"fields":[
{
"textFields":[
{
"text":"Congratulations",
"textSize":"12"
},
{
"text":"Best Wishes",
"textSize":"15"
},
{
"text":"Test text",
"textSize":"10"
}
]
},
{
"imageFields":[
{
"image":"test1.jpg",
"width":"200",
"height":"100"
},
{
"image":"test2.jpg",
"width":"200",
"height":"100"
}
]
}
]
}
My code:
-(void)readJson{
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *fieldsDict =[jsonDict valueForKey:#"fields"];
NSDictionary *textFieldsDict = [fieldsDict valueForKey:#"textFields"];
NSLog(#" Dictionary %# ",textFieldsDict );
}
But its output as follows.
Dictionary (
(
{
text = Congratulations;
textSize = 12;
},
{
text = "Best Wishes";
textSize = 15;
},
{
text = "Test text";
textSize = 10;
}
),
"<null>"
)
It seems like there are two items in dictionary and one is null. I wanted to put three textfield items into the array. How can i solve this.
Don't use SBJSON. Use NSJSONSerialization.
Don't use valueForKey:, use objectForKey:.
You are mixing up dictionaries and arrays. Don't do that. Use NSArray for arrays.
I am revising your code for better understanding
-(void)readJson
{
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *fieldsDict =[jsonDict valueForKey:#"fields"];
NSDictionary *textFieldsDict = [fieldsDict valueForKey:#"textFields"];
NSLog(#" Dictionary %# ",textFieldsDict );
}
More appropriate way is
-(void)readJson
{
NSDictionary *jsonDict = [jsonString JSONValue];
NSArray *fieldsArr =[jsonDict objectForKey:#"fields"];
for(int i=0;i<[fieldArr count];i++)
{
NSArray *textFieldArr = [fieldArr objectAtIndex: i];
for(int j=0;j<[textFieldArr count];j++)
{
NSDictionary *dicTextField = [textFieldArr objectAtIndex: j];
NSString *text = [dicTextField objectForKey: #"text"];
NSString *textSize = [dicTextField objectForKey: #"textSize"];
}
}
}
For quick help
treat { as dictionary and [ as array.
Hope, i am helpful to you.
As your json format, [jsonDict valueForKey:#"fields"] will return an array not dictionary so your code must be
NSDictionary *jsonDict = [jsonString JSONValue];
NSArray *fields = [jsonDict objectForKey:#"fields"];
NSDictionary *fieldsDict = fields[0];
NSArray *textFieldsDict = [fieldsDict objectForKey:#"textFields"];
I have corrected the json format and used NSJSONSerialization,
{"fields":
{"textFields":
[ {"text":"Congratulations", "textSize":"12"},
{"text":"Best Wishes", "textSize":"15"},
{"text":"Test text", "textSize":"10"}
],
"imageFields":
[ {"image":"test1.jpg","width":"200", "height":"100"},
{"image":"test2.jpg", "width":"200", "height":"100"}
]
}
}
-(void)readJson
NSError *e = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e];
NSDictionary *fields = [jsonDict objectForKey:#"fields"];
NSArray *textArray=[fields objectForKey:#"textFields"] ;
NSLog(#"--- %#",textArray );
}

iOS JSon parsing, array in array

I have a simple json format with an array within an array, but I can't figure out how to get the inner array. How do I grab the "Commute" tag as an NSArray or a NSDictionary?
Here is my json:
{
"Language": "EN",
"Place": [
{
"City": "Stockholm",
"Name": "Slussen",
"Commute": [
"Subway",
"Bus"
]
},
{
"City": "Gothenburg",
"Name": "Central station",
"Commute": [
"Train",
"Bus"
]
}
]
}
Here is my code:
NSString *textPath = [[NSBundle mainBundle] pathForResource:#"Places" ofType:#"json"];
NSError *error;
NSString *content = [NSString stringWithContentsOfFile:textPath encoding:NSUTF8StringEncoding error:&error]; //error checking omitted
NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:jsonData
options:kNilOptions
error:&error];
NSArray* AllPlaces = [json objectForKey:#"Place"];
for(int n = 0; n < [AllPlaces count]; n++)
{
PlaceItem* item = [[PlaceItem alloc]init];
NSDictionary* place = [AllPlaces objectAtIndex:n];
item.City = [place objectForKey:#"City"];
item.Name = [place objectForKey:#"Name"];
NSDictionary* commutes = [json objectForKey:#"Commute"];
[self.placeArray addObject:(item)];
}
Your code should be:
NSArray* commutes = [place objectForKey:#"Commute"];
Thwt would give back an array holding "Subway" and "Bus".
I think the problem is the access to json, it should be place instead:
NSArray* commutes = [place objectForKey:#"Commute"];
NSArray *commutes = [place objectForKey:#"Commute"];
This will give you an NSArray with "Subway" and "Bus".
You can considerably shrink you code using KVC Collection Operators:
NSArray *commutes = [json valueForKeyPath:#"Place.#distinctUnionOfArrays.Commute"];
If you want all repeated commutes use #unionOfArrays modifier.

How can I get the JSON array data from nsstring or byte in xcode 4.2?

I'm trying to get values from nsdata class and doesn't work.
here is my JSON data.
{
"count": 3,
"item": [{
"id": "1",
"latitude": "37.556811",
"longitude": "126.922015",
"imgUrl": "http://175.211.62.15/sample_res/1.jpg",
"found": false
}, {
"id": "3",
"latitude": "37.556203",
"longitude": "126.922629",
"imgUrl": "http://175.211.62.15/sample_res/3.jpg",
"found": false
}, {
"id": "2",
"latitude": "37.556985",
"longitude": "126.92286",
"imgUrl": "http://175.211.62.15/sample_res/2.jpg",
"found": false
}]
}
and here is my code
-(NSDictionary *)getDataFromItemList
{
NSData *dataBody = [[NSData alloc] initWithBytes:buffer length:sizeof(buffer)];
NSDictionary *iTem = [[NSDictionary alloc]init];
iTem = [NSJSONSerialization JSONObjectWithData:dataBody options:NSJSONReadingMutableContainers error:nil];
NSLog(#"id = %#",[iTem objectForKey:#"id"]);
//for Test
output = [[NSString alloc] initWithBytes:buffer length:rangeHeader.length encoding:NSUTF8StringEncoding];
NSLog(#"%#",output);
return iTem;
}
how can I access every value in the JSON? Please help me.
look like this ..
NSString *jsonString = #"your json";
NSData *JSONdata = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
if (JSONdata != nil) {
//this you need to know json root is NSDictionary or NSArray , you smaple is NSDictionary
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
if (jsonError == nil) {
//every need check value is null or not , json null like ( "count": null )
if (dic == (NSDictionary *)[NSNull null]) {
return nil;
}
//every property you must know , what type is
if ([dic objectForKey:#"count"] != [NSNull null]) {
[self setCount:[[dic objectForKey:#"count"] integerValue]];
}
if ([dic objectForKey:#"item"] != [NSNull null]) {
NSArray *itemArray = [dic objectForKey:#"item"]; // check null if need
for (NSDictionary *itemDic in itemArray){
NSString *_id = [dic objectForKey:#"id"]; // check null if need
NSNumber *found = (NSNumber *)[dic objectForKey:#"found"];
//.....
//.... just Dictionary get key value
}
}
}
}
I did it by using the framework : http://stig.github.com/json-framework/
It is very powerfull and can do incredible stuff !
Here how I use it to extract an item name from an HTTP request :
(where result is the JSO string)
NSString *result = request.responseString;
jsonArray = (NSArray*)[result JSONValue]; /* Convert the response into an array */
NSDictionary *jsonDict = [jsonArray objectAtIndex:0];
/* grabs information and display them in the labels*/
name = [jsonDict objectForKey:#"wine_name"];
Hope this will be helpfull
Looking at your JSON, you are not querying the right object in the object hierarchy. The top object, which you extract correctly, is an NSDictionary. To get at the items array, and the single items, you have to do this.
NSArray *items = [iTem objectForKey:#"item"];
NSArray *filteredArray = [items filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:#"id = %d", 2];
if (filteredArray.count) NSDictionary *item2 = [filteredArray objectAtIndex:0];
Try JSONKit for this. Is is extremely simple to use.
Note sure if this is still relevant, but in iOS 5, apple added reasonable support for JSON. Check out this blog for a small Tutorial
There is no need to import any JSON framework. (+1 if this answer is relevant)

Resources