Please help me debug this code
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:#"http://cnapi.iconnectgroup.com/api/UserProfile?id=1"]];
NSString *json = [NSString stringWithContentsOfURL:urls encoding:NSASCIIStringEncoding error:&error];
NSLog(#"JSon data = %# and Error = %#", json, error);
if(!error)
{
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSLog(#"JSON data is :: %#", myJsonArray);
for(NSDictionary *jsonDictionary in myJsonArray)
{
//NSString *uids = jsonDictionary[#"UID"];
NSString *address1 = jsonDictionary[#"Address1"];
NSString *address2 = jsonDictionary[#"Address2"];
NSString *city = jsonDictionary[#"City"];
NSString *emailId = jsonDictionary[#"EmailID"];
NSString *fname = jsonDictionary[#"FName"];
NSString *fax = jsonDictionary[#"Fax"];
NSString *lname = jsonDictionary[#"LName"];
NSString *password = jsonDictionary[#"Password"];
NSString *phone = jsonDictionary[#"Phone"];
NSString *state = jsonDictionary[#"State"];
NSString *uids = [jsonDictionary objectForKey:#"UID"];
NSString *zip = jsonDictionary[#"Zip"];
NSString *company = jsonDictionary[#"company"];
NSString *department = jsonDictionary[#"department"];
NSLog(#"Uid is = %#", uids);
NSLog(#"First Name = %#", fname );
NSLog(#"Last Name = %#", lname);
NSLog(#"Company = %#", company);
NSLog(#"Email Id = %#", emailId);
NSLog(#"Password = %#", password);
NSLog(#"Department = %#", department);
NSLog(#"Address 1 = %#", address1);
NSLog(#"Address 2 = %#", address2);
NSLog(#"City = %#", city);
NSLog(#"State = %#", state);
NSLog(#"Zip = %#", zip);
NSLog(#"Phone = %#", phone);
NSLog(#"Fax = %#", fax);
}
}
});
[activity stopAnimating];
self.activity.hidden = YES;
}
Image will give you where the error is. I get this error after clicking stepover to debug. I also tried
NSString *address1 = [jsonDictionary objectForKey:#"Address1"];
From the output of url, it shows it's not array but a dictionary. You are trying to convert to array here.
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
instead use this
NSDictionary *myJsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
then remove that for loop no need of it. and replace your variable jsonDictionary with myJsonDictionary so to retrieve values.
// for(NSDictionary *jsonDictionary in myJsonArray)
Run now it will be fine. Worked for me fine
If the output was array of Dictionaries it would have been looked like this with square brackets around.
For Ex: [{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]
If you are not sure of nature of response from url you can check for
the type. For ex:
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(#"its an array!");
NSArray *myJsonArray = (NSArray *)jsonObject;
// Handle Array of Dictionary
for(NSDictionary *jsonDictionary in myJsonArray)
{
NSString *address1 = jsonDictionary[#"Address1"];
//and so on
}
}
else {
NSLog(#"It's Dictionary");
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSLog(#"jsonDictionary - %#",jsonDictionary);
//Handle NSDictionary
}
jsonDictonary is a NSString not as you expect NSDictonary.
Double check your JSON and maybe before calling that function check if it's NSDictonary.
Your should use one of the semi-standard frameworks for parsing JSON into Core Data. There are some SO questions about those.
In this case, your JSON has only one object which is not an array.
In general, your app shouldn't abort if server sent something unexpected, so it's better to use a parser which will loudly complain about malformed JSON than with it from scratch.
Related
Im loading a database from a website through JSON. When I download the database I use UTF8 to make all characters appear correctly and when I NSLOG them it all appears as it should. But when I analyze the data using JSON and afterwards try to filter out just a few of the words, the words with special characters become like this: "H\U00f6ghastighetst\U00e5g" where it should say: "Höghastighetståg".
I have tried to find a way to make the code convert the text back to UTF8 after filtering but somehow I can't make it happen. Would be really helpful for some answers.
NSError *error;
NSString *url1 = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.pumba.se/example.json"] encoding:NSUTF8StringEncoding error:&error];
NSLog(#"Before converting to NSData: %#", url1);
NSData *allCoursesData = [url1 dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *JSONdictionary = [NSJSONSerialization
JSONObjectWithData:allCoursesData
options:kNilOptions
error:&error];
if( error )
{
NSLog(#"%#", [error localizedDescription]);
}
else {
NSMutableArray *allNames = [NSMutableArray array];
NSArray* entries = [JSONdictionary valueForKeyPath:#"hits.hits"];
for (NSDictionary *hit in entries) {
NSArray *versions = hit[#"versions"];
for (NSDictionary *version in versions) {
NSDictionary *properties = version[#"properties"];
NSString *status = [properties[#"Status"] firstObject];
NSString *name = [properties[#"Name"] firstObject];
if ([status isEqualToString:#"usable"]) {
[allNames addObject:name];
}
}
}
NSLog(#"All names: %#", allNames);
}}
try with
+ (NSString *)utf8StringEncoding:(NSString *)message
{
NSString *uniText = [NSString stringWithUTF8String:[message UTF8String]];
NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding];
message = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding];
return message;
}
or
+ (NSString *)asciiStringEncoding:(NSString *)message
{
const char *jsonString = [message UTF8String];
NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
message = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];
return message;
}
and this code can help you
+ (NSDictionary *)jsonStringToObject:(NSString *)jsonString
{
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse;
if (data)
jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
return jsonResponse;
}
+ (NSString *)objectToJsonString:(NSDictionary *)dict
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (jsonData.length > 0 && !error)
{
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return jsonString;
}
return nil;
}
Here's an example of my data:
[
{
code: "DRK",
exchange: "BTC",
last_price: "0.01790000",
yesterday_price: "0.01625007",
top_bid: "0.01790000",
top_ask: "0.01833999"
}
]
I'm trying to retrieve the value for last_price by loading the contents of my NSDictionary into an Array.
NSURL *darkURL = [NSURL URLWithString:#"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSDictionary *darkDict = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
self.darkPosts = [NSMutableArray array];
NSArray *darkPostArray = [darkDict objectForKey:#""];
for (NSDictionary *darkDict in darkPostArray) {...
But my json doesn't have a root element, so what do I do?
Additionally, when using the suggested answer, the output is ("...
- (void)viewDidLoad{
[super viewDidLoad];
NSURL *darkURL = [NSURL URLWithString:#"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSDictionary *darkDict = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
NSString *lastP = [darkDict valueForKey:#"last_price"];
self.dark_label.text = [NSString stringWithFormat: #"%#", lastP];
}
It looks like you are wanting to iterate over your results. The root element is an array not a dictionary so you can just start iterating
NSError *error = nil;
NSArray *items = [NSJSONSerialization JSONObjectWithData:darkData
options:kNilOptions
error:&error];
if (!items) {
NSLog(#"JSONSerialization error %#", error.localizedDescription);
}
for (NSDictionary *item in items) {
NSLog(#"last_price => %#", item[#"last_price"]);
}
If you literally just want to collect an array of the last_price's then you can so this
NSArray *lastPrices = [items valueForKey:#"last_price"];
Convert the JSON to an NSArray with NSJSONSerialization. Then access the value:
NSData *darkData = [#"[{\"code\":\"DRK\",\"exchange\": \"BTC\",\"last_price\": \"0.01790000\",\"yesterday_price\": \"0.01625007\",\"top_bid\": \"0.01790000\"}, {\"top_ask\": \"0.01833999\"}]" dataUsingEncoding:NSUTF8StringEncoding];
NSArray *array = [NSJSONSerialization JSONObjectWithData:darkData
options:0
error:&error];
NSString *value = array[0][#"last_price"];
NSLog(#"value: %#", value);
NSLog output:
value: 0.01790000
If you are having trouble post the code you have written to get some help.
-- updated for new OP code:
The web service returns a JSON array or dictionaries not a JSON dictionary. First you have to index into the array and then index into the dictionary.
NSURL *darkURL = [NSURL URLWithString:#"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSArray *darkArray = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
NSDictionary *darkDict = darkArray[0];
NSString *lastP = [darkDict valueForKey:#"last_price"];
NSLog(#"lastP: %#", lastP);
NSLog output:
lastP: 0.01970000
Note that the two lines:
NSDictionary *darkDict = darkArray[0];
NSString *lastP = [darkDict valueForKey:#"last_price"];
can be replaced with the single line using array indexing:
NSString *lastP = darkArray[0][#"last_price"];
Where the "[0]" gets the first array element which is a NSDictionary and the "[#"last_price"]" gets the names item from the dictionary.
After get string from web service, i need to parse them. But something is going wrong.
Here is my code;
NSString *responseString = [request responseString];
NSLog(#"response String = %#",responseString);
NSData *tempData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSString *innerJson = [NSJSONSerialization JSONObjectWithData:tempData
options:NSJSONReadingAllowFragments error:&error];
NSLog(#"innerJson = %#",innerJson);
NSArray *entries = [NSJSONSerialization JSONObjectWithData:[innerJson dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
NSLog(#"entries = %#",entries);
for (NSDictionary *entry in entries) {
NSLog(#"entry = %#",entry);
NSString *message = [entry objectForKey:#"message"];
NSLog(#"message = %#",message );
NSString* result = [entry objectForKey:#"result"];
NSLog(#"result = %#", result);
}
Here is my output;
innerJson = {"result": false,"message":"message!"}//I need parse this string.
entries = {
message = "message!";
result = 0;
}
entry = message
I am taking error in for loop.
What am i doing wrong?
Thanks for interest and advice.
The problem is that in the line
NSArray *entries = [NSJSONSerialization
you assign the result to NSArray, and your JSON object is a dictionary, so you should assign to NSDictionary. Then the for loop is unnecessary - you can do:
NSDictionary *entries = [NSJSONSerialization JSONObjectWithData:[innerJson dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
NSLog(#"entries = %#",entries);
NSString *message = [entries objectForKey:#"message"];
NSLog(#"message = %#",message );
NSString* result = [entries objectForKey:#"result"];
NSLog(#"result = %#", result);
Read more details in NSJSONSerialization documentation.
I'm not sure - but I guess this code should work for you:
NSString *responseString = [request responseString];
NSLog(#"response String = %#",responseString);
NSData *tempData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
/* assuming it is a dictionary */
NSDictionary *inner = [NSJSONSerialization JSONObjectWithData:tempData
options:NSJSONReadingAllowFragments error:&error];
NSLog(#"inner = %#",inner);
for(id key in inner) {
id value = [inner objectForKey:key];
NSLog(#"key=%#, value=%#", key, value);
}
I'm having some trouble getting to the data I want to in the JSON file. Here is a shortened version of the output from my console:
{
AUD = {
15m = "125.15547";
24h = "124.74";
buy = "121.0177";
last = "125.15547";
sell = "123.44883";
symbol = "$";
};
BRL = {
15m = "120.34";
24h = "120.34";
buy = "120.34";
last = "120.34";
sell = "120.34";
symbol = "R$";
};
CAD = {
15m = "129.08612";
24h = "131.07";
buy = "128.66227";
last = "129.08612";
sell = "129.08612";
symbol = "$";
};
}
I'm trying to parse the file using the built in JSON parsing library. Here is the parser in my viewDidLoad method:
_tickerArray = [NSMutableArray array];
NSURL *tickerDataURL = [NSURL URLWithString:#"https://blockchain.info/ticker"];
NSData *jsonData = [NSData dataWithContentsOfURL:tickerDataURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", dataDictionary);
NSArray *ar = [NSArray arrayWithObject:dataDictionary];
for (NSString *key in [dataDictionary allKeys]) {
for (NSDictionary *dict in ar) {
TickerData *t;
t.currency = [dict objectForKey:key];
t.symbol = [dict objectForKey:#"symbol"];
t.last = [dict objectForKey:#"last"];
[_tickerArray addObject:t];
}
}
I want to store the currency code (like AUD or BRL) into t.currency along with some of the other data contained in the currency dictionary but now my app is crashing.
Error code:
NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil
None of the objects seem to get added to the _tickerArray
Help?
EDIT: Getting the keys to display with the proper data populating other fields:
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", dataDictionary);
for (NSString *key in [dataDictionary allKeys]) {
NSDictionary *dic=[dataDictionary objectForKey:key];
TickerData *t=[[TickerData alloc] init];
t.currency = key;//EDITED
t.symbol = [dic objectForKey:#"symbol"];
t.last = [dic objectForKey:#"last"];
[_tickerArray addObject:t];
}
t is nil, you have to alloc/ init it:
TickerData *t = [[TickerData alloc] init];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", dataDictionary);
//NSArray *ar = [NSArray arrayWithObject:dataDictionary];//REMOVED
for (NSString *key in [dataDictionary allKeys]) {
NSDictionary *dic=[dataDictionary objectForKey:key];//ADDED
for (NSString *dickey in [dic allKeys]) { //MODIFIED
NSDictionary *dict=[dic objectForKey:dicKey];//ADDED
TickerData *t=[[TickerData alloc] init];//ALLOC INIT ?
t.currency = key;//EDITED
t.symbol = [dict objectForKey:#"symbol"];
t.last = [dict objectForKey:#"last"];
[_tickerArray addObject:t];
}
}
Your data doesn't contain any array, its all dictionaries, try the above code see comments too..
Hope it works..
Edited:
Yes you have initialize the object too, as suggested above in other answers..
Try it....
NSURL *url = [NSURL URLWithString:#"https://blockchain.info/ticker"];
NSLog(#"API : %#",url);
NSMutableData *jsonData = [NSMutableData dataWithContentsOfURL:url];
NSString *data = [[NSString alloc] initWithBytes: [jsonData mutableBytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
dictionary = [data JSONValue];
NSDictionary *dict = [dictionary objectForKey:#"AUD"];
NSLog(#"%#",dict);
NSString *last = [dict valueForKey:#"last"];
NSLog(#"%#",last);
I am trying to parse a json here but keep on getting errors for some reason. my code is
NSString *string = [NSString stringWithFormat:#"http://api.wunderground.com/api/3c158b3b3cd6ce90/hourly/q/11758.json"];//, query];
NSString *string2 = [string stringByReplacingOccurrencesOfString:#" " withString:#"_"];
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString:string]];
NSError* error;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
NSArray* latestLoans = [res objectForKey:#"forecast"]; //2
NSArray *tmp = [latestLoans valueForKey:#"temp"];
NSLog(#"temp: %#", tmp);
and the error is
temp: (null)
Entity: line 2: parser error : Start tag expected, '<' not found
{
^
I don't get this because the URL is real and gets a response, and I need help with this
What you are looking for, "forecast", does not exist in the response. Perhaps what you are looking for is "hourly_forecast".
NSArray* latestLoans = [res objectForKey:#"hourly_forecast"]; //2
NSArray *tmp = [latestLoans valueForKey:#"temp"];