Convert JSON formatted NSString to NSMutableDictionary - iphone

I have a string I'm getting from JSON.
{
"Audit_Description": "Request Approved",
"Module_Name": "Resource Request",
"Field_DisplayName": null",
"Previous_Value": Education",
"Current_Value": Employment",
"Modified_Timestamp": "08-02-2013"
},
{
"Audit_Description": "Request Approved",
"Module_Name": "Resource Request",
"Field_DisplayName": null",
"Previous_Value": null",
"Current_Value": null",
"Modified_Timestamp": "08-02-2013"
}
I want to parse data. From JSON, data come in NSString as above.
I want to extract them as key pair value. But I am not able to parse them.
This should be convert in NSMutableDictionary like
for key "Audit_Description" value should be "Request Approved"
Output:
#{
#"Audit_Description" : #"Request Approved",
#"Module_Name" = #"Resource Request",
#"Field_DisplayName" : <null>,
#"Previous_Value" : #"Education",
#"Current_Value" : #"Employment",
#"Modified_Timestamp" : #"08-02-2013"
}
Thanks.

NSError *err = nil;
NSArray *arr = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
// access the dictionaries
NSMutableDictionary *dict = arr[0];
for (NSMutableDictionary *dictionary in arr) {
// do something using dictionary
}
That creates a mutable dictionary thanks to NSJSONReadingMutableContainers.

Related

Converting JSON Data from NSData to NSDictionary

I have a PHP service that returns me the following response in NSData format. After converting the same into NSString using:
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
I get the following:
[
{
"Emp_Name": "Krishna Mamidi",
"Emp_Designation": "Driver",
"Emp_Type": "Permanent",
"Joining_Date": "05-MAR-2011",
"Salary": 10000
},
{
"Emp_Name": "Aditya Reddy",
"Emp_Designation": "supervisor",
"Emp_Type": "Permanent",
"Joining_Date": "06-MAR-2011",
"Salary": 9000
},
{
"Emp_Name": "Rajiv krishna",
"Emp_Designation": "director",
"Emp_Type": "Permanent",
"Joining_Date": "01-MAR-2011",
"Salary": 100000
}
]
The above is in correct JSON Format.
Having received the NSData format of the above, I use the following to convert the same into JSON Dictionary:
NSError *error = nil;
id jsonObject = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONWritingPrettyPrinted error:&error];
NSDictionary *deserializedDictionary = nil;
if (jsonObject != nil && error == nil)
{
if ([jsonObject isKindOfClass:[NSDictionary class]])
{
//Convert the NSData to NSDictionary in this final step
deserializedDictionary = (NSDictionary *)jsonObject;
}
}
However the "deserializedDictionary" is always null or empty. Basically it never came inside the If Loop above.
I have been trying to figure this out for a while and am not able to. Please help
Your json object is an array try with NSArray instead of NSDictionary.
Because the JSON returned is an array, not a dictionary. Try:
NSLog(#"%#", NSStringFromClass([jsonObject class]));

JSON Arrays and Sorting

I have this json array which I have outlined below. I want to know how I could get all the strings under the "name" key only and place in a certain array to be sorted alphabetically by name and later split into further arrays in accordance to the first letter in the names. Any guide to carrying this out will be much appreciated, thanks. I am using the json kit via github and also NSJSONserialization.
{
"proj_name": "Ant",
"id":
[
{
"name": "David"
},
{
"name": "Aaron"
}
]
},
{
"proj_name": "Dax",
"id":
[
{
"name": "Adrian"
},
{
"name": "Dan"
}
]
}
Here is sample that selects just names and sort them alphabetically. Replace responseData with your data object.
NSMutableArray *names = [[NSMutableArray alloc] init];
NSError* error;
NSArray* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
for (NSDictionary *proj in json) {
NSArray *ids = [proj objectForKey: #"id"];
for (NSDictionary *name in ids)
{
[names addObject: [name objectForKey: #"name"];
}
}
NSArray *sortedNames = [names sortedArrayUsingSelector: #selector(localizedCaseInsensitiveCompare:)];
Go to http://json.bloople.net/ in this link you can see the structure of your JSON response.
from the above response i can see the response as follow:
Project name: Dax
id : 0 name : Adrian
1 name : Dan
So you can use the NSjsonserialization class from Apple. No need to use JSON kit.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"Your URL"]]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"url=%#",request);
id jsonObject = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:nil];
if ([jsonObject respondsToSelector:#selector(objectForKey:)])
{
Nsstring *projectname=[jsonObject objectForKey:#"proj_name"];
NSArray *name_array=[jsonObject objectForKey:#"id"];
NSLog(#"projectname=%#",projectname);
NSLog(#"name_array=%#",name_array);
}
Assuming you've successfully parsed the JSON into an NSArray, you can simplify things pretty dramatically:
NSArray *names = [parsedArray valueForKeyPath:#"#distinctUnionOfArrays.id.name"];
The names array should now contain all of the names flattened into a single array. To sort them, you could then do:
NSArray *sortedNames = [names sortedArrayUsingDescriptors:#[[NSSortDescriptor
sortDescriptorWithKey:#"description" ascending:YES]]];
Or all at once:
NSArray *sortedNames = [[parsedArray valueForKeyPath:#"#distinctUnionOfArrays.id.name"]
sortedArrayUsingDescriptors:#[[NSSortDescriptor
sortDescriptorWithKey:#"description"
ascending:YES]]];
The sortedNames array would now contain:
<__NSArrayI 0x713ac20>(
Aaron,
Adrian,
Dan,
David
)

How to retrive data from json

I am new to iPhone development. I got json as response.
How to separate the Drug value from the json string below:
{"arrCDrugEntity":
[
{
"DrugID":1,
"Drug":"Benadril",
"Quantity":"",
"Comment":"",
"FunctionStatus":false,
"ResultString":"",
"ErrorString":""
},
{
"DrugID":2,
"Drug":"Dcold",
"Quantity":"",
"Comment":"",
"FunctionStatus":false,
"ResultString":"",
"ErrorString":""
},
{
"DrugID":3,
"Drug":"Dolo",
"Quantity":"",
"Comment":"",
"FunctionStatus":false,
"ResultString":"",
"ErrorString":""
},
{
"DrugID":4,
"Drug":"Paracitamol",
"Quantity":"",
"Comment":"",
"FunctionStatus":false,
"ResultString":"",
"ErrorString":""
},
{
"DrugID":5,
"Drug":"Panadol",
"Quantity":"",
"Comment":"",
"FunctionStatus":false,
"ResultString":"",
"ErrorString":""
},
{
"DrugID":6,
"Drug":"Pudin Hara",
"Quantity":"",
"Comment":"",
"FunctionStatus":false,
"ResultString":"",
"ErrorString":""
}
],
"FunctionStatus":true,
"UserID":-1,
"DeliveryAddress":"",
"ResultString":"",
"ErrorString":""
}
Import SBJson.h in your class and use JSONValue method for converting json string into dictionary.
NSDictionary *dict = [yourJsonString JSONValue];
NSArray *arr = [dict valueForKey:#"arrCDrugEntity"];
NSMutableArray *drugArray = [[NSMutableArray alloc] init];
for (NSDictionary *drug in arr) {
[drugArray addObject:[drug valueForKey:#"Drug"]];
}
NSLog(#"drugArray:%#",drugArray);
I think it will be helpful to you.
NSString *str=#"http://your_web_server/your_file....";
NSURL *url=[NSURL URLWithString:str];
NSData *data=[NSData dataWithContentsOfURL:url];
NSError *error=nil;
id *response=[NSJSONSerialization JSONObjectWithData:data options:
NSJSONReadingMutableContainers error:&error];
NSLog("Your JSON Object: %# Or Error is: %#, response, error);
Following code for retrive json data
Dictionary *json = [myString JSONValue];
// Get the objects you want, e.g. output the second item's client id
NSArray *items = [json valueForKeyPath:#"arrCDrugEntity"];
NSLog(#" client Id : %#", [[items objectAtIndex:1] objectForKey:#"clientId"]);
May this help you
You can use NSJSONSerialization for doing this.
NSData *response = [yourJSONString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: response options: NSJSONReadingMutableContainers error: &err];
First put your JSON through a JSON formatter before pasting it, easier to read, use this website
http://jsonformatter.curiousconcept.com/
Secondly, find good JSON parser, personally I use SBJSON, found here
http://stig.github.com/json-framework/
Once you have that downloaded, quite easy to parse, like this, example below
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"drugData" ofType:#"json"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
NSString *responseString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
NSDictionary *MainJSON = [responseString JSONValue];
NSArray *array = [MainJSON valueForKey:#"arrCDrugEntity"];
for(int i = 0; i < [array count]; i++)
{
NSDictionary *temp = [array objectAtIndex:i];
NSLog(#"%#", [temp valueForKey:#"Drug"]);
}
Edit: Updated loop, better way of parsing it, as means you can loop through each individual drug object, so easier if you want to parse the data into a drug object class if you need to
Use this code
#import "JSONKit.h"
NSDictionary *dictionary = [stringData objectFromJSONString];
NSArray *arrayOfDrugs=[NSArray alloc] initWithArray:[dictionary valueForKey:#"arrCDrugEntity"];
for (NSDictionary *drugDic in arrayOfDrugs)
{
NSLog(#"drug id is :%#",[drugDic valueForKey:#"DrugID"]);
NSLog(#"drug is :%#",[drugDic valueForKey:#"Drug"]);
NSLog(#"Quantity is :%#",[drugDic valueForKey:#"Quantity"]);
NSLog(#"Comment is :%#",[drugDic valueForKey:#"Comment"]);
NSLog(#"FunctionStatus is :%i",[[drugDic valueForKey:#"FunctionStatus"] intValue]);
NSLog(#"ResultString is :%#",[drugDic valueForKey:#"ResultString"]);
NSLog(#"ErrorString is %#",[drugDic valueForKey:#"ErrorString"]);
}
with simple JSON Files
but you have to disable ARC in build setting for JSON file.

Couldn't parse data using Json on IOS 5

I try to grab some data with json on ios 5. but i fail...
could someone help me and tell me why it didn't work out.
here's my implementation code
define :
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#define kLatestKivaLoansURL [NSURL URLWithString:#"http://jaksport.com/jarray.php"] //2
then in the viewdidload :
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
this is the function:
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* key = [json objectForKey:#"price"]; //2
NSLog(#"value: %#", key); //3
}
this is the json file:
{
"prices":
{
"price":[
{
"id":1,
"name":"Rosie Gradas",
"beer":4.5,
"cider":4.5,
"guinness":4
},
{
"id":2,
"name":"Wicked Wolf",
"beer":5,
"cider":4.5,
"guinness":4
},
{
"id":3,
"name":"Cafe Posh",
"beer":6,
"cider":5.5,
"guinness":5.5
},
{
"id":4,
"name":"My House",
"beer":16,
"cider":15.5,
"guinness":15.5
}
]
}
}
the nslog always print out null value
The error is in how you acces the objects in your JSON :
{
"prices":
{
"price":[
{
"id":1,
"name":"Rosie Gradas",
"beer":4.5,
"cider":4.5,
"guinness":4
}
}
Given a JSON like that to access the price array you use a syntax like this
NSArray *price = [[json objectForKey:#"prices"]objecForkey:#"price"];
Check the URL in web browser, Your URL is Not A proper JSON.
Link for JSON Verification : JSON Verification

How to parse my JSON data in IOS5

Can anyone tell me how to parse my json data in IOS5. I'm providing my JSON data below:
{
"fieldType" : "Alphanumeric",
"fieldName" : "Name"
},{
"fieldType" : "Numeric",
"fieldName" : "Card Num"
},{
"fieldType" : "Alphanumeric",
"fieldName" : "Pin Num"
}
Also is this JSON format correct or do I need to change the JSON format? When I try to parse JSON using below code I get an error:
The operation couldn’t be completed. (Cocoa error 3840.)
The code I'm using:
NSError *error = nil;
NSData *jsonData = [filedList dataUsingEncoding:[NSString defaultCStringEncoding]];
if (jsonData)
{
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (error)
{
NSLog(#"error is %#", [error localizedDescription]);
// Handle Error and return
return;
}
NSArray *keys = [jsonObjects allKeys];
// values in foreach loop
for (NSString *key in keys)
{
NSLog(#"%# is %#",key, [jsonObjects objectForKey:key]);
}
}
else
{
// Handle Error
}
The JSON data is not correctly formatted. Since you have an array of items, you need to enclose this in [ ... ]:
[
{
"fieldType" : "Alphanumeric",
"fieldName" : "Name"
},{
"fieldType" : "Numeric",
"fieldName" : "Card Num"
},{
"fieldType" : "Alphanumeric",
"fieldName" : "Pin Num"
}
]
Now JSONObjectWithData gives you an NSMutableArray of NSMutableDictionary objects (because of the NSJSONReadingMutableContainers flag).
You can walk through the parsed data with
for (NSMutableDictionary *dict in jsonObjects) {
for (NSString *key in dict) {
NSLog(#"%# is %#",key, [dict objectForKey:key]);
}
}
In any type of parsing, first of all NSLog the JSON or XML string then start writing your parsing your code.
In your case as per the JSON string you mentioned its a array of dictionaries, and once you got your jsonObjects do this to get your data..
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",jsonObjects);
// as per your example its an array of dictionaries so
NSArray* array = (NSArray*) jsonObjects;
for(NSDictionary* dict in array)
{
NSString* obj1 = [dict objectForKey:#"fieldType"];
NSString* obj2 = [dict objectForKey:#"fieldName"];
enter code here
enter code here
}
In this way you can parse the your json string.. for more details go through this tutorial by Raywenderlich.