How to create json Object with NSData in Objective C? - iphone

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

Related

How to format a ReturnString Array from a webService

I get a returnString from a WebService in iOS:
[
{"datum":"2013-07-24
09:38:43","nummer":"1017348010239480212208","anmerkung":"Elektronische
Auftragsdaten wurden vom Versender
\u00fcbermittelt"},{"datum":"2013-07-24
09:38:44","nummer":"1017348010239480212208","anmerkung":"Sendung in
Verteilung"},{"datum":"2013-07-24
09:38:44","nummer":"1017348010239480212208","anmerkung":"Sendung in
Verteilung"},{"datum":"2013-07-24
09:38:44","nummer":"1017348010239480212208","anmerkung":"Sendung in
Zustellung"},{"datum":"2013-07-24
09:26:06","nummer":"1017348010239480212208","anmerkung":"Empf\u00e4nger
nicht angetroffen - benachrichtigt"},{"datum":"2013-07-19
06:24:42","nummer":"1017348010239480212208","anmerkung":"Sendung in
Post-Empfangsbox eingelangt"}
]
the Objective C Code works fine:
#import "SBJson.h"
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
self.textfeld.text = [NSString stringWithFormat: #"%#", returnString];
I try to format the Response with NSMutableArray or NSArray and JSONValue but without success :
NSMutableArray *meinErgebnis = [responseString JSONValue];
NSLog(#"%#",[[meinErgebnis objectAtIndex:0] objectAtIndex:1]);
How to format the returnCode like that?
Nummer: 1017348010239480212208
Anmerkung: Sendung in Verteilung
Nummer: 1017348010239480212208
Anmerkung: Sendung in Post-Empfangsbox
You can obtain Data with following method,
id Data = [NSJSONSerialization JSONObjectWithData:fetchedData options:kNilOptions error:&error];
Then you can loop the data accordingly. For your example,
for(id object in Data)
{
NSLog(#"%#",[object valueForKey:#"nummer"]);
NSLog(#"%#",[object valueForKey:#"anmerkung"]);
}
The loop used above is of fast Enumeration type. Hope this helps.
Use following code for get all the values of nummer and anmerkung from your mutable array.
NSMutableArray *meinErgebnis = [responseString JSONValue];
for(int i = 0; i < meinErgebnis.count; i++)
{
NSLog(#"%#",[[meinErgebnis objectAtIndex:i] objectForKey:#"nummer"]);
NSLog(#"%#",[[meinErgebnis objectAtIndex:i] objectForKey:#"anmerkung"]);
}

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 do I extract a value from the following code?

How do I extract just the "token" value from the following code? I'm looking to save this value into a string.
Is meta an array? If so how would I extract the data from the "token" value?
thanks for any help
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
Response ==> {"meta":[],"data":{"token":"IVZ2ciRkbVtDLUl3YmhwOTkyXzpRR1M3LUUsRiElfWF6T3I6dCxsRWg6di1XcyR6OTUzZHhVazdLTEJ7blU5O258d2xRTXg0VUxwQXBlNHRSOXd2VXZ1aG1RfFhQQjJsSkkoc2IuOTFyYkYodyhAe2RldXR1aDF3RClXWyhoMiU="}}
2013-07-19 15:10:23.139 appName [11190:907] {
data = {
token = "IVZ2ciRkbVtDLUl3YmhwOTkyXzpRR1M3LUUsRiElfWF6T3I6dCxsRWg6di1XcyR6OTUzZHhVazdLTEJ7blU5O258d2xRTXg0VUxwQXBlNHRSOXd2VXZ1aG1RfFhQQjJsSkkoc2IuOTFyYkYodyhAe2RldXR1aDF3RClXWyhoMiU=";
};
meta = (
);
}
I believe the data is in JSON format. In that case, this should work.
NSError *error = nil;
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&error];
NSString *token = [[responseDict objectForKey:#"data"] objectForKey:#"token"];
I'd just do this:
NSData *responseData = [NSData dataWithContentsOfURL:yourURL];
NSString *token = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions error:NULL][#"data"][#"token"];
It will be nil if there's any error.
In your Case, meta is an Array and data is a Dictionary. If your Response is properly formatted in JSON then you can use the below sample code to get the TokenString and metaArray.
Sample Code :
NSData *data = [NSData dataWithContentsOfURL:yourURL];
NSError* error = nil;
NSDictionary* responseDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *token = [[responseDict objectForKey:#"data"] objectForKey:#"token"];
NSArray *meta = [responseDict objectForKey:#"meta"];
NSLog(#"\ntoken :: %#\nmeta :: %#",token,meta);
PS : To know more about JSON response , take a look at this Answer.

Break String that came from Json

I have a String that I got from a webserver which came in json format, but the string is huge with everything in it. I tried using the NSDICTIONARY but to no success. I was wondering what would be the best approach to break this string and add to different strings and eventually put it all in a class of strings. Thanks for the help! Here is my code:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://mym2webdesign.com/meiplay/paulsuckedabuffalo/artists.php"]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //Or async request
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSError *error=nil;
NSLog(#"HHHHHHHHHHHHHH"); //use this to know how far Im getting
NSLog(returnString); // Look at the console and you can see what the restults are
/*NSDictionary *results = [returnString JSONValue];
NSString *ID = [results objectForKey:#"ID"]; // for example
NSLog(#"ID Number: %#", ID);*/
Here is some of the log i get:
[{"ID":"1","name":"kevin","bio":"kevins bio"},{"ID":"1","name":"kevin","age":"20"},{"ID":"2","name":"Cesar","bio":"Cesar bio"},{"ID":"2","name":"Cesar","age":"19"},{"ID":"3", "name":"Katherine", "bio":"Katherines bio"},{"ID":"3", "name":"Katherine", "age":"22"}]
You are doing it wrong. Its a NSArray of NSDictionaries. So first you need to assign it to NSArray and then loop over it to get each individual NSDictionary. See below.
NSArray *results = [returnString JSONValue];
for(NSDictionary *record in results)
{
NSLog(#"ID: %#", [record objectForKey:#"ID"]);
}
You'll probably be better off just using NSJSONSerialization if your app is targeted for at or over iOS 5.0:
NSArray *JSONArray = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:&error];
You might need to experiment with using NSArray vs. NSDictionary, etc., but this should be an overall simpler solution.
Try this :
NSArray *results = [returnString JSONValue];
for (int i=0; i<[results count];i++) {
NSDictionary *DetailDictonary=[results objectAtIndex:i];
NSString *strid=[DetailDictonary objectForKey:#"ID"];
NSString *strName=[DetailDictonary objectForKey:#"name"];
NSString *strBio=[DetailDictonary objectForKey:#"bio"];
// Or You can set it in Your ClassFile
MyClass *classObj=[[MyClass alloc] init];
classObj.strid=[DetailDictonary objectForKey:#"ID"];
classObj.strName=[DetailDictonary objectForKey:#"name"];
classObj.strBio=[DetailDictonary objectForKey:#"bio"];
[YourMainArray addObject:classObj]; //set YourClass to Array
[classObj release];
}

Parse JSON - 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"];
}
}