Pulling Data From JSON - objective-c

I have a simple JSON string that looks like
(
{
ID = 1;
response = Yes;
}
)
And my NSDictionary is not pulling the objectForKey. The jsonArray is displaying correctly. My code:
hostStr = [[hostStr stringByAppendingString:post] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *hostURL = [NSURL URLWithString:hostStr];
NSString *jsonString = [[NSString alloc] initWithContentsOfURL:hostURL];
self.jsonArray = [jsonString JSONValue];
[jsonString release];
NSLog(#"%#", jsonArray);
NSDictionary *infoDictionary = [self.jsonArray objectForKey:#"ID"];
NSLog(infoDictionary);

This is probably the case since you have completely invalid JSON (test it out at http://jsonlint.com/). Because you are missing the quotation marks in your JSON the elements won't match the id ID. All object names/keys need to be in quotation marks.
You're lucky that your framework interprets your invalid JSON (somehow) correctly so that you actually get an array or a dictionary. Because of this the result of NSLog will be correct.
Rewrite your JSON like this to get it working:
{
"ID": 1,
"response": "YES"
}
(Also be sure that jsonArray is a NSDictionary)

Related

Obj-C, encode Simplified Chinese in an iTunes search querystring?

I'm struggling to use the iTunes search API with Simplified Chinese. I've tried a couple of character variations (provided by google translate) along with HTML encoding the characters.
The code below doesn't cause any errors but it doesn't give me any results, unlike English words. I've also tried different Chinese words.
However I'm not sure how to proceed.
NSString *url_string = #"";
NSString *keyword = [#"Chéngfǎ" stringByReplacingOccurrencesOfString: #" "
withString: #"%20"];
//NSString *keyword = [#"乘法" stringByReplacingOccurrencesOfString: #" "
withString: #"%20"];
url_string = [NSString stringWithFormat:
#"https://itunes.apple.com/search?term=%#&country=%#&entity=software", keyword, #"cn"];
NSError *error;
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString: url_string]];
NSMutableArray *json;
if (data != nil)
{
json = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error: &error];
}
NSDictionary *outer = [json valueForKey: #"results"];
for(NSDictionary *item in outer)
{
//results
}
I tried to type the URL into browser and I get the results. I think you need to percent encode the chinese characters?
https://itunes.apple.com/search?term=%E4%B9%98%E6%B3%95&country=cn&entity=software
You can use iOS function stringByAddingPercentEncodingWithAllowedCharacters.

Add dictionaries to nsdictionary as value for key

I have to prepare a dictionary for serialization and then post it to server. Dictionary may have several other dictionaries as values for #"items" key. But some brackets interrupt. And server response me an error html.
NSMutableArray *a = [[NSMutableArray alloc]init];
for(int i = 0; i < [self.cartCopy count]; i++) {
NSString *itemNumber = [NSString stringWithFormat:#"%d", i + 1];
NSDictionary *tempDict = #{ itemNumber : #{
#"item_id" : [[self.cartCopy objectAtIndex:i]objectForKey:#"id"],
#"quantity" : [[self.cartCopy objectAtIndex:i]objectForKey:#"quantity"],
#"type" : [[self.cartCopy objectAtIndex:i]objectForKey:#"type"],
#"color_id" : #"0",
}
};
[a addObject:tempDict];
}
NSDictionary *dict = #{
#"date":oDate,
#"address":oAddress,
#"name":oName,
#"shipping_date":oShippingDate,
#"receiver_phone":oReceiverPhone,
#"customer_phone":oCustomerPhone,
#"total_price": oTotalPrice ,
#"additional_info": #"asd",
#"items": a
};
UPDATE: My NSLog of string after [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:nil] :
{"address":"asd",
"name":"asd",
"receiver_phone":"123",
"customer_phone":"123",
"total_price":"1",
"date":"2013-03-05 21:22:55",
"additional_info":"asd",
"items":[
{"1":{
"type":"2",
"color_id":"0",
"item_id":10,
"quantity":"3"
}
},
{"2":{
"type":"1",
"color_id":"0",
"item_id":74,
"quantity":"3"
}
}
],
"shipping_date":"2030-03-03 12:12:12"
}
I think the reason is square brackets. How can i delete them?
For example, it works perfectly with dictionary:
NSDictionary *dict = #{
#"date":oDate,
#"address":oAddress,
#"name":oName,
#"shipping_date":oShippingDate,
#"receiver_phone":oReceiverPhone,
#"customer_phone":oCustomerPhone,
#"total_price": oTotalPrice ,
#"additional_info": #"asd",
#"items": #{
#"1":#{
#"type":#"1",
#"color_id":#"0",
#"item_id":#"1",
#"quantity":#"1"
},
#"2":#{
#"type":#"1",
#"color_id":#"0",
#"item_id":#"1",
#"quantity":#"1"
}
}
};
In your example that works perfectly the items object is a dictionary with keys {1, 2}.
In your output JSON your items object is an array.
This array contains 2 objects, each one is a dictionary.
The first contains a single key {1}.
The second contains a single key {2}.
You just need to remove the array and use a dictionary instead to store these dictionaries.
That looks as if you want to send JSON to the server. You can create JSON data from your dictionary with
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
If you need it as a string:
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

Parse json response in object c from http get request

i'm trying to parse the response i get from a http get request in object c, i have do this:
NSString *returnValue = [[NSString alloc] initWithData:oRespondeData encoding:NSUTF8StringEncoding];
SBJsonParser *jParser = [[SBJsonParser alloc] init];
NSDictionary *JSONresponse = [jParser objectWithString:returnValue];
then i search for a specific key:
NSArray *jSon1 = [JSONresponse objectForKey:#"links"];
and in the array there is only one element, and if i log it i have this:
NSLog(#"%#",[jSon1 objectAtIndex:0]);
log:
(
"Video.720p.X264-..",
"",
"http://video/dl/Video.720p.X264-.."
)
how i can get the url with http? i have tried everything, i have also tried to trim the string to delete the whitespaces, but seems that it's not a nsstring because i receive
[__NSArrayM stringByTrimmingCharactersInSet:]: unrecognized selector sent to instance
how i can do?
[jSon1 objectAtIndex:0]
is returning an array of 3 separate strings, so if yo'ure trying to get the 3rd string you could do:
NSArray *links = [jSon1 objectAtIndex:0];
NSString *httpUrl = [links objectAtindex:2];
Hopefully i understand your question correctly.

How to convert a JSON array into an NSArray

I've been having trouble finding out how to convert a JSON array into an NSArray.
I have a php script that creates an array that is converted into JSON which is then sent and stored into an NSString that looks like:
[1,2,3,4]
My problem is that I need to make that into an NSArray of ints. How would one do that?
Thanks!
You should look at the documentation of the NSJSONSerialization class.
You can hand it the NSData received from a remote call that is a string in JSON format and receive the array or dictionary it contains.
NSObject *o =[NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
// other useful "options":
// 0
// NSJSONReadingMutableLeaves
// NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers
you should then check that o is of the type you expect for sanity purposes
If I wanted to quickly break that into an array I would do it like this:
NSString * jstring = #"[1,2,3,4]"; //your json string
jstring = [jstring stringByReplacingOccurrencesOfString:#"[" withString:#""];
jstring = [jstring stringByReplacingOccurrencesOfString:#"]" withString:#""];
NSArray * intArray = [string componentsSeparatedByString:#","];
//you could create your int from the array like this
int x = [[intArray objectAtIndex:0]intValue];
Import the SBJson in your project (drag and drop it)
#import "SBJson.h"
Then where you receive the JSON response from the php file
NSArray *array = [responseString JSONValue];

Problem with parsing JSON result

I have a problem with parsing a JSON result. This is what I get from my HTTP request:
{"subscriptions": [
{"id":"A", "title":"A title"},
{"id":"B", "title":"B title"},
]}
And this is what I'm doing in my code:
// Getting the result<br>
NSString *str = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
// Creating the JSON parser<br>
SBJSON *parser = [[SBJSON alloc] init];
// Parse result in an object<br>
NSDictionary *result = [parser objectWithString:str];
So far everything works fine. I have one key/value pair in my result object which I think is the subscriptions object. But the problem is now: How can I access the inner objects of it like the id and title?
Thanks for help.
The JSON parser will create nested NSArray and NSDictionary objects for you. To get to the array use:
NSArray *array = [result objectForKey:#"subscriptions"];
Then access the objects in the array like so:
NSDictionary *arrayObject = [array objectForIndex:0];
And finally, to get one of the inner objects do:
NSString *stringObject = [arrayObject objectForKey:#"id"];