Parse JSON - iPhone - iphone

I'm new with json, and I need your help please.
I received JSON string like this :
{"network":
{
"network_id":111,
"name":"test name",
"city":"test city",
"country":"test country",
"description":"test desc"
}
}
How I can handle this string and split key/value in order to use them in my view ?
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
//*********** How I can parse responseString *********//
[networkIDLabel setText:#"ADD THE VALUE"];
[nameLabel setText:#"ADD THE VALUE"];
[responseString release];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
thanks

In iOS 5 and later, you can parse the response data directly with NSJSONSerialization:
[NSJSONSerialization JSONObjectWithData:self.responseData …];
If you want to support earlier versions of iOS, you can use JSONKit.

In objective-c json can be represnted as Dictionary
-(void)getData:(NSData*)response{
// You have to include the SBJSON or else you can also use the NSJSONSerialization
//NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&erro];
SBJSON *parse = [[SBJSON alloc]init];
NSString *jsonString = [[NSString alloc] initWithData:response
encoding:NSUTF8StringEncoding];
NSDictionary *jsonData = [parse objectWithString:jsonString error:&erro];
NSDictionary *insideData = [jsonData objectForKey:#"network"];
if(![insideData isKindOfClass:[NSNull class]])
{
NSString *data1 = [insideData objectForKey:#"network_Id"];
NSString *data2 = [insideData objectForKey:#"name"];
}
}

Related

create a json string from NSArray

In my iPhone aplication I have a list of custom objects. I need to create a json string from them. How I can implement this with SBJSON or iPhone sdk?
NSArray* eventsForUpload = [app.dataService.coreDataHelper fetchInstancesOf:#"Event" where:#"isForUpload" is:[NSNumber numberWithBool:YES]];
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
NSString *actionLinksStr = [writer stringWithObject:eventsForUpload];
and i get empty result.
This process is really simple now, you don't have to use external libraries,
Do it this way, (iOS 5 & above)
NSArray *myArray;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
I love my categories so I do this kind of thing as follows
#implementation NSArray (Extensions)
- (NSString*)json
{
NSString* json = nil;
NSError* error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return (error ? nil : json);
}
#end
Although the highest voted answer is valid for an array of dictionaries or other serializable objects, it's not valid for custom objects.
Here is the thing, you'll need to loop through your array and get the dictionary representation of each object and add it to a new array to be serialized.
NSString *offersJSONString = #"";
if(offers)
{
NSMutableArray *offersJSONArray = [NSMutableArray array];
for (Offer *offer in offers)
{
[offersJSONArray addObject:[offer dictionaryRepresentation]];
}
NSData *offersJSONData = [NSJSONSerialization dataWithJSONObject:offersJSONArray options:NSJSONWritingPrettyPrinted error:&error];
offersJSONString = [[NSString alloc] initWithData:offersJSONData encoding:NSUTF8StringEncoding] ;
}
As for the dictionaryRepresentation method in the Offer class:
- (NSDictionary *)dictionaryRepresentation
{
NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
[mutableDict setValue:self.title forKey:#"title"];
return [NSDictionary dictionaryWithDictionary:mutableDict];
}
Try like this Swift 2.3
let consArray = [1,2,3,4,5,6]
var jsonString : String = ""
do
{
if let postData : NSData = try NSJSONSerialization.dataWithJSONObject(consArray, options: NSJSONWritingOptions.PrettyPrinted)
{
jsonString = NSString(data: postData, encoding: NSUTF8StringEncoding)! as String
}
}
catch
{
print(error)
}
Try like this,
- (NSString *)JSONRepresentation {
SBJsonWriter *jsonWriter = [SBJsonWriter new];
NSString *json = [jsonWriter stringWithObject:self];
if (!json)
[jsonWriter release];
return json;
}
then call this like,
NSString *jsonString = [array JSONRepresentation];
Hope it will helps you...
I'm a bit late to this party, but you can serialise an array of custom objects by implementing the -proxyForJson method in your custom objects. (Or in a category on your custom objects.)
For an example.

How to create json Object with NSData in Objective C?

How to create json Object with NSData in Objective C. I'm having values in a NSData variable.
You can use it like this in iOS 5 (if you are sure of your json structure you can directly use NSArray or NSDictionary doing a cast)
NSError *jsonError;
id jsonDictionaryOrArray = [NSJSONSerialization JSONObjectWithData:myData options:NULL error:&jsonError];
if(jsonError) {
// check the error description
NSLog(#"json error : %#", [jsonError localizedDescription]);
} else {
// use the jsonDictionaryOrArray
}
if you have a value in NSData object then you can convert it in NSString variable like bellow
NSString *response = [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
Edited...
i am not sure what you want but i give you the json array from string like bellow..
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSError *error;
SBJSON *json = [[SBJSON new] autorelease];
NSArray *arrData = [json objectWithString:responseString error:&error];
[responseString release];
you can get data in array
hope this help you mate...
:)
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"youur link"]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
if([jsonObjects isKindOfClass:[NSArray class]]){
//Is array
}else if([jsonObjects isKindOfClass:[NSDictionary class]]){
//is dictionary
}else{
//is something else
}
EDIT FOR SWIFT
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>] {
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}

how can i parse a json string into nsdictionary?

i am writing code for login application. can anyone help me how to parse a json string?
my code is
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *loginDict = [parser objectWithString:loginDict error:nil];
[loginStatus release];
[connection release];
Example data:
NSString *strData = #"{\"1\": {\"name\": \"Jerry\",\"age\": \"12\"}, \"2\": {\"name\": \"Bob\",\"age\": \"16\"}}";
NSData *webData = [strData dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];
NSLog(#"JSON DIct: %#", jsonDict);
NSLog output:
JSON DIct: {
1 = {
age = 12;
name = Jerry;
};
2 = {
age = 16;
name = Bob;
};
}
//*************Static Resopnse
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"demo" ofType:#"text"];
NSLog (#"Content: %#", filePath);
NSString *content = [[[NSString alloc] initWithContentsOfFile:filePath
usedEncoding:nil
error:nil] autorelease];
SBJSON *json = [[SBJSON new] autorelease];
NSString *str=[[NSString alloc]initWithString:content];
dictTemp = [json objectWithString:str error:nil];
NSLog(#"Actions is: %#",dictTemp);
NSArray *arr=[[dictTemp valueForKey:#"Data"] mutableCopy];
arrX=[[NSMutableArray alloc] init];
arrY=[[NSMutableArray alloc] init];
for(NSDictionary *dict in arr)
{
[arrX addObject:[dict valueForKey:#"Milestone"]];
[arrY addObject:[dict valueForKey:#"Sites"]];
}
NSLog(#"X is: %#",[arrX description]);
NSLog(#"Y is: %#",[arrY description]);
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]
NSLog([[loginStatus JSONValue] description],nil);
//This will give you parsed output.
NSString *responseString = [[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding];
NSlog(#"json String is: %#",responseString);
NSDictionary *dictionary = [responseString JSONValue];
NSLog(#"Dictionary value is %#", [dictionary objectForKey:#"json"]);
the result of this code is:json String is: {"json":{"Success":"Activation code."}}
After Conversation the result is ------- Dictionary value is {
Success = "Activation code."};

issue in parsing json and displaying data

i am using the below json method and following code to parse json method and display the data which i need on a label.
i followed this link http://www.touch-code-magazine.com/tutorial-fetch-and-parse-json/ and many other but i am not getting the result what i need.Either it throws exception in below code line or else it displays null value.
NSDictionary* profile = [profileinfo objectAtIndex:0]; //throws exception
can anyone help me what is wrong in the below code and what is missing so tat i get the values i.e, phonenumber,firstname and other data from json method.
//Json Method
{
"createdBy":"superadmin",
"createdOn":"2011-11-15T00:49:06+05:30",
"updatedBy":"superadmin",
"updatedOn":"2011-11-15T00:49:06+05:30",
"contactNumber":"9945614074",
"emailNotification":"true",
"firstName":"resident2",
"lastName":"user5",
"loginId":"jin",
"married":"false",
"message":"",
"preferredLanguage":"ko_KR",
"sex":"0",
"smsNotification":"false",
"status":"ACTIVE",
"subscribedPlans":"Intelligent Concierge",
"userName":"Cisco"
}
//code
- (void)loadData
{
dataWebService = [[NSMutableData data] retain];
NSURLRequest *request = [[NSURLRequest requestWithURL:[NSURL URLWithString:#"URL LINK"]]retain];
[[NSURLConnection alloc]initWithRequest:request delegate:self];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:dataWebService encoding:NSUTF8StringEncoding];
self.dataWebService = nil;
NSArray* profileinfo = [(NSDictionary*) [responseString JSONValue] objectForKey:#"createdBy"];
[responseString release];
NSDictionary* profile = [profileinfo objectAtIndex:0];
//fetch the data
NSNumber* numb = [profile objectForKey:#"contactNumber"];
NSString* name = [profile objectForKey:#"firstName"];
//set the text to the label
label.numberOfLines = 0;
label.text = [NSString stringWithFormat:#"contactNumber: %# \n \n Name: %# \n \n",
numb,name];
}
The jsonValue is your dictionary.
replace
NSArray* profileinfo = [(NSDictionary*) [responseString JSONValue] objectForKey:#"createdBy"];
and
NSDictionary* profile = [profileinfo objectAtIndex:0];
with
NSDictionary * profile = (NSDictionary*)[responseString JSONValue];
and now use objectForKey to get your values

How to read the JSON value on console in iphone

i have the following json value in console:
{"TokenID":"kuiHigen21","isError":false,"ErrorMessage":"","Result":[{"UserId":"153","FirstName":"Rocky","LastName":"Yadav","Email":"rocky#itg.com","ProfileImage":null,"ThumbnailImage":null,"DeviceInfoId":"12"}],"ErrorCode":900}
this is my server api :#"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login"
//api takes 5 parameters .
when i post data to server api values are posted to server and i get the above response in json format.
i want to parse the above the JSON value that i get in the response and save in sqlite database.
i am doing this code to parse the above JSON value:
-(void)connectionDidFinishLoadingNSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] lengthwebData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
self.webData = nil;
SBJSON *parser =[[SBJSON alloc]init];
NSURLRequest *request = [NSURLRequest requestWithURLNSURL URLWithString"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login.json"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
//NSDictionary *object = [parser objectWithString:json_string error:nil];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [status objectForKey"Login"],[status objectForKey"LoginKey"]);
[connection release]; [webData release];
}
You should check out some of the JSON parsers, my personal favourite is json-framework. After you've included one of them in your project, where you've got your JSON response from your server:
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *statuses = [result objectForKey:#"Result"];
which will return your array of results (where each object in the array is an NSDictionary).
You can save this to a database with the help of a model class, Result
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *values = [result objectForKey:#"Result"];
NSMutableArray *results = [[NSMutableArray alloc] init];
for (int index = 0; index<[values count]; index++) {
NSMutableDictionary * value = [values objectAtIndex:index];
Result * result = [[Result alloc] init];
result.UserId = [value objectForKey:#"UserId"];
result. FirstName = [value objectForKey:#"FirstName"];
...
[results addObject:result];
[result release];
}
use the array of results to save it to the database.
for (int index = 0; index<[results count]; index++) {
Result * result = [results objectAtIndex:index];
//save the object variables to database here
}