IOS how to replace json data using their keys - ios

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

Related

Fetch JSON Response Into Propertylist For UITableview

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

how to search and replace in NSDictionary?

I have a JSON that I converted into NSDictionary and now I want to search and replace some values in it but I have no idea how to to this,
{
"CODE":200,
"APICODERESULT":"USER_INTERESTS",
"MESSAGE":"user interests fetched successfully",
"VALUE":{
"Books":[
{
"key":"7",
"value":"Fiction",
"selected":true
},
{
"key":"8",
"value":"Romantic",
"selected":true
}
],
"Music":[
{
"key":"11",
"value":"Classical",
"selected":false
},
{
"key":"12",
"value":"Jazz",
"selected":false
},
{
"key":"10",
"value":"Pop",
"selected":false
},
{
"key":"13",
"value":"Western",
"selected":false
}
]
}
}
here I have the value for key that I want to search in the dictionary and when I found that key with the value that I have I want to replace the value for selected in the same block.
For example:-
I have value 10 for key then I want to change the value for key selected to true
so the it will look like this
{
"CODE":200,
"APICODERESULT":"USER_INTERESTS",
"MESSAGE":"user interests fetched successfully",
"VALUE":{
"Books":[
{
"key":"7",
"value":"Fiction",
"selected":true
},
{
"key":"8",
"value":"Romantic",
"selected":true
}
],
"Music":[
{
"key":"11",
"value":"Classical",
"selected":false
},
{
"key":"12",
"value":"Jazz",
"selected":false
},
{
"key":"10",
"value":"Pop",
"selected":true
},
{
"key":"13",
"value":"Western",
"selected":false
}
]
}
}
Consider your input dictionary as mainDictionary and use following code:
NSMutableDictionary *valuesDic = [mainDictionary objectForKey:#"VALUES"];
NSArray *allPossibleKeysArray = [valuesDic allKeys];
for (int j=0; j<allPossibleKeysArray.count; j++) {
NSString *keyStr = [allPossibleKeysArray objectAtIndex:j];
NSArray *array = [valuesDic objectForKey:keyStr];
for (int i=0; i<array.count; i++) {
NSMutableDictionary *dictionary = [array objectAtIndex:i];
NSString *keyString = [NSString stringWithFormat:#"%#",[dictionary objectForKey:#"key"]];
if([keyString isEqualToString:keyvalue]){
[dictionary removeObjectForKey:#"selected"];
[dictionary setObject:[NSNumber numberWithBool:true] forKey:#"selected"];
}
}
}
Hope this helps!!
You should make such changes during parsing the JSON/moving it into model. The code below is a workaround:
NSDictionary *initialJson = //Your JSON here
NSArray *allSubKeys= [initialJson[#"Value"] allKeys];
// Your mutable output.
NSMutableDictionary *mutableJson = [initialJson mutableCopy]
for(NSString *key in allSubKeys) {//Music && Books
// Create another cointainer here
for(NSArray *arr in mutableJson[#"Value][key]) {
// Create another cointainer here
for(NSDictionary *dict in arr) {//key, value, selected
for (NSString *key2 in [dict allKeys]) {
if ([key2 isEqualToString:#"selected"] && [dict[#"value"] equals:#10]) {
// Save YES here
}
else {
// Just copy element
}
// Add object to parent container
}
// Add object to parent container
}
// Add object to parent container
}
// Add object to parent container
}
Here is full solution
NSString* str=#"{\"CODE\":200,\"APICODERESULT\":\"USER_INTERESTS\",\"MESSAGE\":\"user interests fetched successfully\",\"value\":{\"Books\":[{\"key\":\"7\",\"value\":\"Fiction\",\"selected\":true},{\"key\":\"8\",\"value\":\"Romantic\",\"selected\":true}],\"Music\":[{\"key\":\"11\",\"value\":\"Classical\",\"selected\":false},{\"key\":\"12\",\"value\":\"Jazz\",\"selected\":false},{\"key\":\"10\",\"value\":\"Pop\",\"selected\":false},{\"key\":\"13\",\"value\":\"Western\",\"selected\":false}]}}";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"dictionary before updating: %#", dictionary);
// copy old dict
NSMutableDictionary* newDict=[[[NSMutableDictionary alloc]init]autorelease];
[newDict addEntriesFromDictionary:dictionary];
// get the entry to be changed
NSMutableDictionary* valueDict=[[[NSMutableDictionary alloc]init]autorelease];
[valueDict addEntriesFromDictionary:newDict[#"value"]];
NSMutableArray* musicArray=[[[NSMutableArray alloc] init] autorelease];
[musicArray addObjectsFromArray:newDict[#"value"][#"Music"]];
// get the music array and change your property
NSMutableDictionary* musicDict2=[[[NSMutableDictionary alloc] init] autorelease];
[musicDict2 addEntriesFromDictionary:[musicArray objectAtIndex:2]];
[musicDict2 setValue:[NSNumber numberWithBool:YES] forKey:#"selected"];
[musicArray replaceObjectAtIndex:2 withObject:musicDict2];
// update the value dictionary
[valueDict setObject:musicArray forKey:#"Music"];
//update the new dictionary
[newDict setObject:valueDict forKey:#"value"];
NSLog(#"dictionary after updating: %#", newDict);

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

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