I'been trying to parse JSON data retrieved from my server, but when the server sends JSON with accents or question marks, it shows as null values.
It would be great if someone could help me solve this issue.
Here is my code
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *urls=[NSString stringWithFormat:#"http://myserver.myserver/myserver"];
NSLog(#"%#",urls);
NSURL *url =[NSURL URLWithString:urls];
NSData* data = [NSData dataWithContentsOfURL:url];
//fetch the data to the JSON Foundation opject.
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
//process the JSON Foundation object to the view.
[self processData:json];
}
-(void)processData:(NSDictionary *) JSONObject{
NSString *kl = [JSONObject valueForKey:#"qlk"];
NSString *an= [JSONObject valueForKey:#"alk"];
NSString *bn = [JSONObject valueForKey:#"blk"];
NSString *cn =[JSONObject valueForKey:#"clk"];
NSString *dn =[JSONObject valueForKey:#"dlk"];
NSString *correcta =[JSONObject valueForKey:#"rlk"];
qkl.text=pregunta;
akl.text =an;
bkl.text =bn;
ckl.text=cn;
dkl.text=dn;
}
And the JSON
{ "qlk": "¿De qué color es el caballo blanco de Simon Bolivar?", "alk": "Negro", "blk": "Cafe", "clk": "Blanco", "dlk": "Rojo", "rlk": "c" }
Thanks.
Related
I am retriving some file from the web containing data in a specific format which I would like to parse. However I know only how to get the file from the web:
dispatch_async(server_queue, ^{
NSData* data = [NSData dataWithContentsOfURL:
kURL];
[self performSelectorOnMainThread:#selector(parseData:)
withObject:data waitUntilDone:YES];
});
In the parse method I would like to tokenize each line of the file but I am not sure how to extract the lines from the NSData object.
-(void)parseData:(NSData *)responseData {
//tokenize each line of responseData
}
Any suggestion?
NSData is not in a format where you can go through to parse it. Just convert it to a NSString like this:
-(void)parseData:(NSData *)responseData
{
NSString *stringFromData = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSArray *eachLineOfString = [stringFromData componentsSeparatedByString:#"\n"];
for (NSString *line in eachLineOfString) {
// DO SOMETHING WITH THIS LINE
}
}
I want to add value to a response. But the response is in this format
{
"participants": [
{
"lat_long": "0.0,0.0",
"name": "alma"
}
],
"lat_long": "0.0,0.0",
"_id": "52a80a5dccb8137326000027"
}
How can I add values to the keys name & lat_long. I am using Sbjson method.
Thanks in advance.
NSURL * url=[NSURL URLWithString:#"Give your URL Here"];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableDictionary * jsonDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"%#",jsonDic);
NSMutableArray * jsonArray=jsonDic[#"participants"];
NSLog(#"%#",jsonArray);
NSString * str =[jsonArray valueForKey:#"lat_long"];
NSString * str1 =[jsonArray valueForKey:#"name"];
NSLog(#"%#",str);
NSLog(#"%#",str1);
Try this code.
I'm not sure, what you are asking about, but This helps you to get the keys of the Disctionary .
NSDictionary *json = [NSJSONSerialization .....//Parsed JSon
NSMutableDictionary *arrCopy = [json mutableCopy];
NSArray *keys= [json allKeys];
for (NSString *keysV in keys){
NSLog(#"Keys are %#", keysV);
if ([keysV isEqualToString:#"_id"]) {
[arrCopy setValue:#"121213211323" forKey:keysV];
}else if (){
}.......................
}
NSLog(#"After Value added: %#", arrCopy);
I am new to iOS and working on the GOOGLE-MAP-SDK. Everything is going very well, but I am not able to use the annotations in this case due to which I am not able to locate my positions which I fetched from the placeAPI of Google.
So kindly help me out with my errors.
Code File
-(IBAction)search:(id)sender
{
NSString *url = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=30.7343000,76.7933000&radius=500&types=food&name&sensor=true&key=AIzaSyCGeIN7gCxU8baq3e5eL0DU3_JHeWyKzic"];
//Formulate the string as URL object.
NSURL *googleRequestURL=[NSURL URLWithString:url];
// Retrieve the results of the URL.
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
//The results from Google will be an array obtained from the NSDictionary object with the key "results".
NSArray* places = [json objectForKey:#"results"];
//Write out the data to the console.
NSLog(#"Google Data: %#", places);
}
Here is the code from which I will receive the data and want to display it on the Google map. NSLog(#"Google Data: %#", places); is giving me the out put...
I am trying to get Dictionary form json, but the following code dosent seem to work. I am getting the JSON, but cannot get the dictionary from it.
NSString *str = [[NSMutableString alloc] initWithData:responseCust encoding:NSUTF8StringEncoding];
NSLog(#"CUSTOMER string -----################ %#", str);
if(str.length>5)
{
SBJSON *jsonparser=[[SBJSON alloc]init];
NSDictionary *res= [jsonparser objectWithString:str];
NSLog(#"Contants Results %#",res);
[jsonparser release];
[str release];
}
Thank You.
Please Follow the below code
NSURL * url=[NSURL URLWithString:str];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
//Get json data in Dictionary
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSLog(#"%#",json);
try this one..
Use NSJSONSerialization and make use of
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error to convert JSON to foundation object.
hope this helps
Just try to Either
NSDictionary *dict = [str JSONValue];
NSLog(#"%#", dict);
OR
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseCust options:nil error:&error];
NSLog(#"%#", dict);
+(NSDictionary *)converJsonStringToDictionary:(NSString *)jsonString
{
NSString *stringToConvert = jsonString;
if (![self isObjectEmpty:stringToConvert]) {
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *convertedData = nil;
convertedData = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (error != nil){
DLog(#"Error converting jsonString to dictionary: %#", [error description]);
convertedData = nil;
}
else if ([convertedData isKindOfClass:[NSDictionary class]]) {
DLog(#"The converted data is of kind NSDictionary");
}
else if ([convertedData isKindOfClass:[NSArray class]]){
DLog(#"The converted data is of kind NSArray");
convertedData = nil;
}
else{
DLog(#"The converted data is not NSDictionary/NSArray");
convertedData = nil;
}
return convertedData;
}
else{
DLog(#"The received jsonString is nil")
return nil;
}
}
Here, try adding the encoding...
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
NSLog(#"dict: %#", jsonDict);
Check here for some samples on how to handle json on objective-c
I have searched online for solution toward this problem, but the result that is always returned to me is null.
This is the following string that I received from a web. Everything seems to work fine. However, when I were to convert this string into an array then the result returned is null.
The code:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSLog(#"Succeeded! Received %d bytes of data",[self.responseData length]);
// String
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", responseString);
NSDictionary *resultsDictionary = [responseString objectFromJSONString];
NSLog(#"%#", resultsDictionary); // Returns null
}
The result:
[{"cid":"382595836","name":"\u514d\u7a0e\u5e97\u4e13\u5356\u54c1"},{"cid":"382595837","name":"\u9650\u91cf\u7248\u9999\u6c34"},{"cid":"380837083","name":"\u5973\u58eb\u7cbe\u88c5"},{"cid":"380837082","name":"\u7537\u58eb\u7cbe\u88c5"},{"cid":"61540749","name":"\u7b80\u88c5\u5973\u7528\u9999\u6c34"},{"cid":"24213689","name":"\u7b80\u88c5\u7537\u7528\u9999\u6c34"},{"cid":"25541561","name":"Q\u9999\u5973\u58eb"},{"cid":"25541841","name":"Q\u9999\u7537\u58eb"}]
May anyone provide me a way to think through this.
Thanks.
try this
NSMutableData *responseData; // use in .h class
use this function in use in .m class
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"connection did receive data");
[responseData appendData:data];
NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]];
NSLog(#"%#",responseString);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data", [responseData length]);
}
Use below code. The code will work on ios 5.0 and later.
NSArray* list = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions
error:&error];
I did this. It's working fine for me. Can you try below one logic.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"demo" ofType:#"json"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
NSError *error;
id json = [NSJSONSerialization JSONObjectWithData:myData options:kNilOptions error:&error];
NSArray *list = (NSArray *)json;
The objectFromJSONString will return nil if the string you're passing in isn't valid JSON.
I checked this
[{"cid":"382595836","name":"\u514d\u7a0e\u5e97\u4e13\u5356\u54c1"},{"cid":"382595837","name":"\u9650\u91cf\u7248\u9999\u6c34"},{"cid":"380837083","name":"\u5973\u58eb\u7cbe\u88c5"},{"cid":"380837082","name":"\u7537\u58eb\u7cbe\u88c5"},{"cid":"61540749","name":"\u7b80\u88c5\u5973\u7528\u9999\u6c34"},{"cid":"24213689","name":"\u7b80\u88c5\u7537\u7528\u9999\u6c34"},{"cid":"25541561","name":"Q\u9999\u5973\u58eb"},{"cid":"25541841","name":"Q\u9999\u7537\u58eb"}] 2012-11-30 14:29:52.779 com.JSON.Product[1979:c07]
in JSONLint it shows it is an invalid JSON.