UITextView prints JSON identifier instead of desired parsed data - php

Like the title says, my UITextView is setup to print data found within "userName". Instead of behaving appropriately, it prints "userName".
PHP code:
<?php
header('Content-Type: application/json');
$arr = array ('userName'=>'derekshull', 'userBio'=>'This is derekshulls bio','userSubmitted'=>'15');
echo json_encode($arr);
?>
Objective C:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *myURL = [[NSURL alloc]initWithString:#"http://techinworship.com/json.php"];
NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL];
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:&error];
if(!error)
{
for (id element in jsonArray) {
textview.text = [NSString stringWithFormat:#"%#", [element description]];
// text view will contain last element from the loop
}
}
else{
textview.text = [NSString stringWithFormat:#"Error--%#",[error description]];
}
}
What am I missing here? Also, when run, the application does not crash and give error. However, the following is documented in the DeBug Area.
2014-03-24 20:20:53.258 testtest[11434:60b] Unknown class textview in Interface Builder file.

I don't currently have a OSX computer available so I can't evaluate my code.
It seems like the array you have in you PHP code is an associative array and the JSON will be similar. When you are parsing the JSON string in your Obj-C code try assigning it to a NSDictionary, this way you will have access to the associative array.
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:&error];
When using the data in the jsonArray don't iterate it, use the NSDictionary method objectForKey to get get the value you want.
As an example, to get the value of userName, you can do this:
[jsonArray objectForKey: #"userName"] // jsonArray is not actually a array, but a dictionary now
And to change the text of the textview, you can do the following:
textview.text = [NSString stringWithFormat:#"%#", [jsonArray objectForKey: #"userName"]];
Ask if something is unclear!
Cheers!

Related

Parsing a $_POST formatted as an array in php

I receive a funnily formatted $_POST submission in a php script being sent in the form:
{"receipt-data":"MILGDgYJKoZIhvcNAQcCoILF..."}
If I print the $_POST variable I get an Array(), sometimes empty sometimes containing a dictionary "receipt-data":"...." (I was not yet able to understand why sometimes it is empty and sometimes not).
Before it started to arrive empty, I tried to print the first element, but got nothing interesting.
Briefly, what is the correct way to intercept such a posting and get the value corresponding to receipt-data?
This the (quite long) Post data of which I took off some chunks in order to remain in the maximum message allowance:
Array
(
[{"receipt-data":"MILOdwYJKoZIhvcNAQcCoILOaDCCzmQCAQExCzAJBgUrDgMCGgUAMIK_KAYJKoZIhvcNAQcBoIK_GQSCvhUxgr4RMAoCAQgCAQEEAhYAMAoCARQCAQEEAgwAMAsCAQECAQEEAwIBADALAgEDAgEBBAMMATgwCwIBCwIBAQQDAgEAMAsCAQ4CAQEEAwIBGzALAgEPAgEBBAMCAQAwCwIBEAIBAQQDAgEAMAsCARkCAQEEAwIBAzAMAgEKAgEBBAQWAjQrMA0CAQ0CAQEEBQIDARHWMA0CARMCAQEEBQwDMS4wMA4CAQkCAQEEBgIEUDIzMTAYAgEEAgECBBB/lJHT84oy2t4czXgoc79YMBsCAQACAQEEEwwR
[...]
Ugb2YgdGhlIHRoZW4gYXBwbGljYWJsZSBzdGFuZGFyZCB0ZXJtcyBhbmQgY29uZGl0aW9ucyBvZiB1c2UsIGNlcnRpZmljYXRlIHBvbGljeSBhbmQgY2VydGlmaWNhdGlvbiBwcmFjdGljZSBzdGF0ZW1lbnRzLjANBgkqhkiG9w0BAQUFAAOCAQEAXDaZTC14t_2Mm9zzd5vydtJ3ME\/BH4WDhRuZPUc38qmbQI4s1LGQEti_9HOb7tJkD8t5TzTYoj75eP9ryAfsfTmDi1Mg0zjEsb_aTwpr\/yv8WacFCXwXQFYRHnTTt4sjO0ej1W8k4uvRt3DfD0XhJ8rxbXjt57UXF6jcfiI1yiXV2Q\/Wa9SiJCMR96Gsj3OBYMYbWwkvkrL4REjwYDieFfU9JmcgijNq9w2Cz97roy\/5U2pbZMBjM3f3OgcsVuvaDyEO2rpzGU_12TZ\/wYdV2aeZuTJC_9jVcZ5_oVK3G72TQiQSKscPHbZNnF5jyEuAF1CqitXa5PzQCQc3sHV1ITGCAcswggHHAgEBMIGjMIGWMQswCQYDVQQGEwJVUzETMBEGA1UECgwKQXBwbGUgSW5jLjEsMCoGA1UECwwjQXBwbGUgV29ybGR3aWRlIERldmVsb3BlciBSZWxhdGlvbnMxRDBCBgNVBAMMO0FwcGxlIFdvcmxkd2lkZSBEZXZlbG9wZXIgUmVsYXRpb25zIENlcnRpZmljYXRpb24gQXV0aG9yaXR5AggYWUMhcnSc\/DAJBgUrDgMCGgUAMA0GCSqGSIb3DQEBAQUABIIBADAfG0M5Lzrl9bhrTKD9nR18Q8HO6zC6XaGtCYtf8a7cE8voswN59EkVCr0yMpcwYxmRjTllJBxJwbPKx3u81B7shTzN5xYfe26nuKqDZBZDo7FqWZSDOhcZ\/E6TEylmWg6kHmWXZJuebDFnLKhQwsgl3H\/atOW4eywXAij_OvPBwPiPc9IBgq4u35oqQL5d2YV38ukBi\/ToqT97\/WG5qvb1JsUDdFoqRuJyA4CCaa8dBlZGDJar29_CjsniFJDz9\/NtUcepZTy3T78POFe2cr_Enrl8E9drcrS4xe5Um9R_CVDNwCgoD1bwYA7M5CjrzNO1dqiXLE59d1i3hgSMS4UxnGLGlXFmlF7DZsjwZil7Eec3XtIaJUlLgnkipOuVUqD1nYw6oBAkCursLDC9AlroN5kWMcEXQXRUgRCItvntJoN897cJX6uXpaaSbiDgXbrwTqnM3/tzHjJgI5T68eI5Dp0LDdxT5FcSd_y3sePf4eTNrJN/eQDMb44ytDg7GOIsG/qiPyHzunp2FrTZZWBIdDP1MvFmLsRoDqvutNqmX5lw3Hobghzk] => "}
)
Upon parsing it with:
$json=json_encode($_POST);
$data=json_decode($json, TRUE);
$data takes the form:
{"{\"receipt-data\":\"MILP9wYJKoZIhvcNAQcCoILP6DCCz_QCAQExCzAJBgUrDgMCGgUAMIK\/qAYJKoZIhvcNAQcBoIK\/mQSCv5Uxgr_RMAoCAQgCAQEEAhYAMAoCARQCAQEEAgwAMAsCAQECAQEEAwIBADALAgEDAgEBBAMMATgwCwIBCwIBAQQDAgEAMAsCAQ4CAQEEAwIBGzALAgEPAgEBBAMCAQAwCwIBEAIBAQQDAgEAMAsCARkCAQEEAwIBAzAMAgEKAgEBBAQWAjQrMA0CAQ0CAQEEBQIDARHWMA0CARMCAQEEBQwDMS4wMA4CAQkCAQEEBgIEUDIzMTAYAgEEAgECBBB5fbMSc4WXteSuDDZ20X4pMBsCAQACAQEEEwwRUHJvZHVjdGlvblNhbmRib3gwHAIBBQIBAQQU6dWy7_Sty19JvZ97C3lbZ7GoJG4wHgIBDAIBAQQWFhQyMDE1LTAxLTAxVDIwOjU4OjUxWjAeAgESAgEBBB
[...]
b24gQXV0aG9yaXR5AggYWUMhcnSc\/DAJBgUrDgMCGgUAMA0GCSqGSIb3DQEBAQUABIIBABjGnbWvGn1GhGrK99iWdL_fezRcgTN961IxTFvxt0Ob69SEgVgM\/99DbAOdE5xmVNkXucdNXY6RakQ\/CgoD1bwYA7M5CjrzNO1dqiXLE59d1i3hgSMS4UxnGLGlXFmlF7DZsjwZil7Eec3XtIaJUlLgnkipOuVUqD1nYw6oBAkCursLDC9AlroN5kWMcEXQXRUgRCItvntJoN897cJX6uXpaaSbiDgXbrwTqnM3\/tzHjJgI5T68eI5Dp0LDdxT5FcSd_y3sePf4eTNrJN\/eQDMb44ytDg7GOIsG\/qiPyHzunp2FrTZZWBIdDP1MvFmLsRoDqvutNqmX5lw3Hobghzk":"\"}"}
It is the result of executing the objective-c code:
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:storeURL];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSDictionary *requestContents = #{
#"receipt-data": [self.receipt base64EncodedStringWithOptions:0]
};
NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestContents
options:0
error:&error];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:requestData];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:theRequest queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
[...]
From looking at the code that creates the request we can see that it is sending the data formatted as JSON, so you will first want to run it through json_decode, e.g.
$data=json_decode($_POST[0], TRUE);
You don't need to run it through json_encode first as it has already been sent to you as JSON.
Then for the "receipt-data" value itself, we can see that the objective-c code encodes it as base64, so you need to decode it using base64_decode:
$data['receipt-data'] = base64_decode($data['receipt-data']);

unable to retrieve json data in objective-c

I'm trying to retrieve json data from mysql database in iphone. This is my .php file.
I would like to retrieve this data so that I have some code in my .m
- (void)jsonParse{
NSString* path = #"http://phdprototype.tk/getResultData.php";
NSURL* url = [NSURL URLWithString:path];
NSString* jsonString = [[NSString alloc]initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
NSDictionary* resultDic = [dic objectForKey:#"maxid"];
NSString* recData = [resultDic objectForKey:#"recommendData"];
NSString* rData = [resultDic objectForKey:#"room"];
NSString* lData = [resultDic objectForKey:#"level"];
NSLog(#"recommendData = %#, room = %#, level = %#",recData,rData,lData);}
What I expect is to get data from recommendData, room, and level, but the debugger windows shows it did not get anything. This is what the debugger shows
2014-03-12 15:13:21.500 Semantic Museum[24289:907] recommendData = (null), room = (null), level = (null)
do I miss something??
Looks a problem with the server response headers.
I am seeing the Content-Type come back as
text/html
but it should be something like
application/json
This issue is coming because it's static text(try to View Source in your browser, it's returning extra parameter with JSON). If it's JSON, you need to check that from PHP the header value is set properly.

how to find array of index from textfield value in Xcode?

i need to get values from mysql and display in Xcode textfield dynamically.( want to automatically enter the string in lastName and phoneNumber when user enters the firstName)
here my Xcode..
NSError *err;
NSString *strURL=[NSString stringWithFormat:#"http://192.168.1.22:81/priya/sam.php"];
NSData *dataURL=[NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *name=firstname.text;
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:dataURL options: NSJSONReadingMutableContainers error:&err];
NSArray *array=[jsonArray objectForKey:#"key"];
lastname.text=[[array objectAtIndex:0]objectForKey:#"lastname"];
phone.text=[[array objectAtIndex:0]objectForKey:#"phone"];
then how to find text array of index using first-name.
thanks in advance
I'm not quite sure what the problem is (do you have only 1 row instead of desired number of rows?)
Shows all rows from received data:
for (NSDictionary *item in array) {
firstname.text=[item objectForKey:#"firstName"];
lastname.text=[item objectForKey:#"lastname"];
phone.text=[item objectForKey:#"phone"];
}
The output you got for server is a dictionary and the parent key is "Key". To get array index dynamically please see the code below
NSMutableArray *infoArray=[[NSMutableArray alloc]init];
infoArray =[jsonArray objectForKey:#"Key"]; // this is your array with all information stored index wise.
NSLog(#"%#", infoArray);
for(int i=0; i<infoArray.count; i++)
{
NSLog(#"%#", [[infoArray objectAtIndex:i]objectForKey:#"firstname"]);
NSLog(#"%#", [[infoArray objectAtIndex:i]objectForKey:#"lastnamename"]);
}
or
The issue is with PHP side ask them to replace "[" and "]" with "(" and ")".
Hope this will help

very basic JSON to tableView (iOS)

Well, I decided that it's time to learn a new skill, programming objective-c. My programming knowledge is very minimal, It consists of PHP, little bit of HTML, and a little bit of MySQL. What I want to do is take some JSON that is made with php and populate a iOS table view.
here is my json.php:
<?php
$array = array(1,2,3,4,5,6,7,8,9,10);
$json = json_encode($array);
echo $json;
?>
My only problem is, is I have no idea where to start on how to use JSONKit framework. https://github.com/johnezang/JSONKit/ I would prefer to use JSONKit over the other alternatives just because it seems it has more support.
NSString *strURL = [NSString stringWithFormat:#"http://api.tekop.net/json.php"];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"%#", strResult);
I was able to print the results of the JSON page in the debug console. Now my only question is what next? I have tried to look for some tutorials online but all I could find was something more advanced Jason phraser. To advanced for my basic needs. I know my questions very vague and open to a lot of different answer, but I figured this is the place to ask these types of questions.
iOS has its own JSON parse now called NSJSONSerialization.
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
You can have a look. I always use it like this.
[NSJSONSerialization JSONObjectWithData:tmpData
options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments
error:nil]
sample by modifying your code:
NSString *strURL = [NSString stringWithFormat:#"http://api.tekop.net/json.php"];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSArray *arrayResult = [NSJSONSerialization JSONObjectWithData:dataURL
options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments
error:nil];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
Something to note is that, if your json is an array based, use NSArray to store the result. If your json is an hash based, use NSDictionary. (Hope I say it clearly, I dont know the related terms to describe)
What have you tried?
NSArray *array = [dataURL objectFromJSONData];
NSAssert([array isKindOfClass:[NSArray class]], #"This should be an array.");
for (NSNumber *value in array) {
NSAssert([value isKindOfClass:[NSNumber class]], #"This should be a number.");
NSLog(#"%#", value);
}

Iphone JSON-Framework EOF Error

I'm attempting to use Json-Framework to parse output (on the iPhone) from my website. The data on the website is an array of news objects... passed through PHP's json_encode().
The JSON Output is here: http://pastebin.com/Be429nHx
I am able to connect to the server and store the JSON data, then I do:
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// Create a dictionary from the JSON string
NSDictionary *results = [jsonString JSONValue];
NSArray *items = [results valueForKeyPath:#"data.array"];
NSLog(#" NewsID : %#", [[items objectAtIndex:1] objectForKey:#"newsID"]);
and I receive the following error from the NSLog() line:
-JSONValue failed. Error is: Didn't find full object before EOF
Event Id : (null)
STATE: <SBJsonStreamParserStateStart: 0x4e3c960>
JSONValue failed. Error is: Token 'key-value separator' not expected before outer-most array or object
Event Id : (null)
Any help will be greatly appreciated... thanks!!!
It might be because your JSON is structured as an array, so you should just do:
NSArray *items = [jsonString JSONValue];
NSLog(#" NewsID : %#", [[items objectAtIndex:1] objectForKey:#"newsID"]);
or, alternately, change the JSON itself so that it's more like:
{"somekeyname":[your existing json array]}

Categories