I try to read a multidimensional array as request from content:
[
{
"content" : {
"parcel" : {
"ServiceParcelEventPostalCode" : "1005",
"ConsigneePostalCode" : "1220 (292)",
"ParcelTypeDescription" : "Paket",
"ReferenceIdentcode" : "1017348010239480212208",
"CustomerShipmentNr" : "N\/A",
"Identcode" : "1017348010239480212208",
"ReferenceNumber" : "D1Lmp8TPN_1",
.......... etc
I'm, trying to get ServiceParcelEventPostalCode without access :
NSString *urlString = #"http://www.post.at/sendungsverfolgung4.php";
NSURL *url = [NSURL URLWithString:urlString];
// URL-Request-Objekt erstellen
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSMutableData *body = [NSMutableData data];
NSString *postWerte = [NSString stringWithFormat:#"id=%#", self.textfeld.text];
[body appendData:[postWerte dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
// Abfrage ans Web senden und Rückgabe in Variable speichern
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
const char *convert = [returnString UTF8String];
NSString *responseString = [NSString stringWithUTF8String:convert];
NSMutableArray *meinErgebnis = [responseString JSONValue];
NSString *wert1 = [NSString stringWithFormat:#"%#",[[[meinErgebnis objectAtIndex:2] objectAtIndex:0] objectForKey:#"ServiceParcelEventPostalCode"]];
Just follow structure of your JSON. [] in JSON means array, {} means dictionary. If JSON in your example is your responseString:
NSMutableArray *jsonArray = [responseString JSONValue];
NSString *postalCode = nil;
if (jsonArray.count)
{
NSDictionary *elementDict = [jsonArray objectAtIndex:0];
NSDictionary *contentDict = [elementDict objectForKey:#"content"];
NSDictionary *parcelDict = [contentDict objectForKey:#"parcel"];
postalCode = [parcelDict objectForKey:#"ServiceParcelEventPostalCode"];
}
Related
Hello everyone I m trying to send two json objects in one request.
Here is what I did so far:
NSDictionary *credentials = [request getCredentials];
NSURL *url = [NSURL URLWithString:#"https://myurl.com"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
req.HTTPMethod = #"POST";
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSError *error = nil;
NSData *o = [NSJSONSerialization dataWithJSONObject:output
options:NSJSONWritingPrettyPrinted error:&error];
NSData *c = [NSJSONSerialization dataWithJSONObject:credentials
options:NSJSONWritingPrettyPrinted error:&error];
NSString *myString = [[NSString alloc] initWithData:o encoding:NSUTF8StringEncoding];
NSLog(#"DATA: %#",myString);
if (!error) {
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:req
fromData:c completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
NSLog(#"RESPONSE %#", response);
}];
[uploadTask resume];
}
In this code I send only "NSData *c" but also I want to send "NSData *o" in the same request. Is it possible, I need your helps. Thanks.
you can combine dictonaries into one using below code then post to server.
#property (nonatomic, strong) NSMutableDictionary *configuration;
...
-(NSMutableDictionary*) configuration{
if (!_configuration) {
NSDictionary *core_config = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"installation" ofType:#"plist"]];
NSDictionary *app_config = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle bundleWithPath:#"/path/to"] pathForResource:#"something/data" ofType:#"plist"]];
[_configuration addEntriesFromDictionary: core_config];
[_configuration addEntriesFromDictionary: app_config];
NSLog(#"merged: %lu, core: %lu, app: %lu", (unsigned long)[_configuration count], (unsigned long)[core_config count], (unsigned long)[app_config count]);
// merged: 0, core: 4, app: 5
}
return _configuration;
}
So I understand how to split the array that holds the JSON info, but what I am stuck on is trying to get it to display everything past only the first whitespace. For instance, if you look at the JSON site (http://iam.colum.edu/portfolio/api/course?json=True) each course has a course number at beginning. I want to split each array object only displaying the course name. For instance, if you look at the site, the first object is "Computer Architecture" second is "Digital Image and Design"... etc. I don't need to know how to split the string, I can already do that, but how do I split it so it takes away "xx-xxx " (x being the course number)? The code I have currently splits at each whitespace, but that's not going to work for obvious reasons.
JSONViewController
dispatch_async(progressQueue, ^{
jstring = [JSONHelper JSONgetString:#"http://iam.colum.edu/portfolio/api/course?json=True"];
dispatch_async(dispatch_get_main_queue(), ^{
//main thread code
//textView.text = jstring;
jarray = [jstring componentsSeparatedByString:#" "];
textView.text = [jarray objectAtIndex:1];
NSString * fullString = [NSString string];
for(int i = 0; i < jarray.count; i++)
{
fullString = [fullString stringByAppendingString:[jarray objectAtIndex:i]];
}
textView.text = fullString;
NSError *error = nil;
NSArray * resultArray = [NSJSONSerialization JSONObjectWithData: [jstring dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error: &error];
if ( !resultArray ) {
NSLog(#"Error parsing JSON: %#", error);
} else {
for(NSString * course in resultArray) {
NSLog(#"Course: %#", course);
}
}
JSONHelper.h
#interface JSONHelper : NSObject
+ (NSDictionary *)JSONget:(NSString *)query;
+ (NSString *)JSONgetString:(NSString *)query;
+ (NSString *)JSONpostString:(NSString *)query;
+(NSString *)JSONpostString:(NSString *)query
withData:(NSString *)jsonData;
#end
JSONHelper.m
#implementation JSONHelper
//returns a dictionar from a get request
+ (NSDictionary *)JSONget:(NSString *)query
{
NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error] : nil;
if (error) NSLog(#"[%# %#] JSON error: %#", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);
return results;
}
//returns JSON string from get request
+(NSString *)JSONgetString:(NSString *)query
{
NSString* searchURL = [NSString stringWithFormat:query];
NSError* error = nil; //error for NSUSRLConnection
NSURLResponse* response = nil;
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
NSURL* URL = [NSURL URLWithString:searchURL];
[request setURL:URL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:30];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error)
{
NSLog(#"Error performing request %#", searchURL);
return 0;
}
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"jsonString:%#", jsonString);
return jsonString;
}
+(NSString *)JSONpostString:(NSString *)query{
NSString* searchURL = [NSString stringWithFormat:query];
NSError* error = nil;
NSURLResponse* response = nil;
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
NSURL* URL = [NSURL URLWithString:searchURL];
[request addValue: #"application/json" forHTTPHeaderField:#"Accept"];
[request addValue: #"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setURL:URL];
[request setTimeoutInterval:15];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error)
{
NSLog(#"Error performing request %#", searchURL);
return 0;
}
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"jsonString:%#", jsonString);
return jsonString;
}
+(NSString *)JSONpostString:(NSString *)query
withData:(NSString *)jsonData
{
NSString* searchURL = [NSString stringWithFormat:query];
NSError* error = nil;
NSURLResponse* response = nil;
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
NSURL* URL = [NSURL URLWithString:searchURL];
[request addValue: #"application/json" forHTTPHeaderField:#"Accept"];
[request addValue: #"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setURL:URL];
[request setTimeoutInterval:30];
NSData* requestData = [jsonData dataUsingEncoding:NSUTF8StringEncoding];
[request addValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:requestData];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error)
{
NSLog(#"Error performing request %#", searchURL);
return 0;
}
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"jsonString:%#", jsonString);
return jsonString;
}
#end
NSDictionary *dictionary = [JSONHelper JSONget:#"http://iam.colum.edu/portfolio/api/course?json=True"];
for (id course in dictionary) {
NSLog(#"%#", [course substringFromIndex:8]);
}
As you can seen all those course number has the same pattern (so I assume that won't change) and it's xx-xxxx (7 character + whitespace after this). In that cas you can easily use substring fromthe index 8 (counting from 0).
Bu if you are still eager on how to do this in case when those course numbers may have various lengths yo can try using this solution:
NSDictionary *dictionary = [JSONHelper JSONget:#"http://iam.colum.edu/portfolio/api/course?json=True"];
for (id course in dictionary) {
NSArray *courseArray = [course componentsSeparatedByString:#" "];
NSMutableString *courseName = [NSMutableString string];
for (int i = 1; i < [courseArray count] ; i++) {
[courseName appendFormat:#"%# ", courseArray[i]];
}
// Deleting last character which is whitespace
[courseName substringToIndex:courseName.length -1];
NSLog(#"%#", courseName);
[courseName setString:#""];
}
It may not be the most efficent way to handle your problem but it just works!
NSURL *url = [[NSURL alloc] initWithString:#"http://nyxmyx.com/Kinkey/KinkeyPHP/lastidretrieve.php"];
NSData *data = [url resourceDataUsingCache:YES];
NSString *string = [[NSString alloc] initWithData:data encoding:NSMacOSRomanStringEncoding];
NSLog(#"result FOR ID %#",string);
I am using this code in didenterBackgroundMethod.In that i just want to call lastidretrieve.php which returns a response as a string.I am getting error as "receiver type nsurl for instance message does not declare a method with selector resourceDataUsingCache".i have no idead about this error.
Use this code instead of your code it gives the string output ,then you have to format that string to get disired output.
NSString *post =#"";
NSURL *url=[NSURL URLWithString:#"http://nyxmyx.com/Kinkey/KinkeyPHP/lastidretrieve.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ([response statusCode] >=200 && [response statusCode] <300)
{
//NSData *data = [responseData resourceDataUsingCache:YES];
NSString *string = [[NSString alloc] initWithData:urlData encoding:NSMacOSRomanStringEncoding];
NSLog(#"responseData-%#",string);
}
Output will be like this.
responseData-1995<br />prabu<br />1231231233<br />antab<br />8080808080<br />1360738531881.jpg<br />No
UPDATE
In case you want to add argument in your URL than change post string to this.
NSString *post =[[NSString alloc] initWithFormat:#"yourArg=%#",yourArg];
It would have been sufficient to read the documentation of NSURL. This method is deprecated. You should use [[NSData alloc] initWithContentsOfURL:url] instead.
I want to get HTML from website. I wrote below code but this returns (null).
NSString *strURL = #"http://www.googole.com";
- (NSString *)getHtml
{
NSURL *url = [NSURL URLWithString: strURL];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest : req
returningResponse : &response
error : &error];
NSString *strData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return strData;
}
I think you have mistyped the url.
It should be NSString *strURL = #"http://www.google.com";
I parse an JSON File into an Dictionary and in a further step I want to build a post request for couchDB.
The parsing works fine, but if I post I get an error. I thinks it has something to do with my escape sequence in the post string.
Here´s the code:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"json"];
NSString *fileContent = [[NSString alloc] initWithContentsOfFile:filePath];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];
// getting the data from file
NSString *_id = (NSString *) [data objectForKey:#"_id"];
NSString *rev_ = self.rev;
NSString *_herausgeber = (NSString *) [data objectForKey:#"Herausgeber"];
NSString *_nummer = (NSString *) [data objectForKey:#"Nummer"];
NSNumber *_deckung = [data objectForKey:#"Deckung"];
NSString *_waerhung = (NSString *) [data valueForKey:#"Waehrung"];
NSDictionary *_inhaber = (NSDictionary *) [data objectForKey:#"Inhaber"];
NSString *_name = (NSString *) [_inhaber objectForKey:#"Name"];
NSString *_vorname = (NSString *) [_inhaber objectForKey:#"Vorname"];
NSNumber *_maennlich = (NSNumber *) [_inhaber objectForKey:#"maennlich"];
NSArray *_hobbys = (NSArray *) [_inhaber objectForKey:#"Hobbys"];
NSString *_hobby0 = [_hobbys objectAtIndex:0];
NSString *_hobby1 = [_hobbys objectAtIndex:1];
NSString *_hobby2 = [_hobbys objectAtIndex:2];
NSNumber *_alter = (NSNumber *) [_inhaber objectForKey:#"Alter"];
NSArray * _kinder = (NSArray *) [_inhaber objectForKey:#"Kinder"];
NSString *_kind0 = [_kinder objectAtIndex:0];
NSString *_kind1 = [_kinder objectAtIndex:1];
NSString *_kind2 = [_kinder objectAtIndex:2];
NSString *_partner = (NSString *) [_inhaber objectForKey:#"Partner"];
[parser release];
//post string:
NSString *post = [NSString stringWithFormat:#"{\"_id\":\"%#\",\"_rev\":\"%#\",\"Herausgeber\":\"%#\",\"Nummer\":\"%#\",\"Deckung\":%#,\"Waehrung\":\"%#\",\"Inhaber\":{\"Name\":\"%#\",\"Vorname\":\"%#\",\"maennlich\":%#,\"Hobbys\":[\"%#\",\"%#\",\"%#\"],\"Alter\":%#,\"Kinder\":[\"%#\",\"%#\",\"%#\"],\"Partner\":%#}}",_id,rev_,_herausgeber,_nummer,_deckung,_waerhung,_name,_vorname,_maennlich,_hobby0,_hobby1,_hobby2,_alter,_kind0,_kind1,_kind2,_partner];
//post header:
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:cdbURL]];
[request setHTTPMethod:#"PUT"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
The Error I get:
Reply: {"error":"bad_request","reason":"invalid UTF-8 JSON:
<<\"{\\"_id\\":\\"161eba7093799b610502bdfba5004281\\",\\"_rev\\":\\"199-bb065cbd0a365b188fc492cc22453d74\\",\\"Herausgeber\\":\\"SAP\\",\\"Nummer\\":\\"1234-5678-9012-3456\\",\\"Deckung\\":2000000,\\"Waehrung\\":\\"Franc\\",\\"Inhaber\\":{\\"Name\\":\\"Mustermann\\",\\"Vorname\\":\\"Max\\",\\"maennlich\\":1,\\"Hobbys\\":[\\"Reiten\\",\\"Golfen\\",\\"Lesen\\"],\\"Alter\\":42,\\"Kinder\\":[\\"Max\\",\\"Moritz\\",\\"Lisa\\"],\\"Partner\\":}}\">>"}
How can I solve this problem?
Personally, I would avoid constructing the JSON post-string myself and instead use SBJson's [NSObject JSONRepresentation] function.
Then you could fill an NSDictionary and have the API construct the JSON for you.
NSString *_id = #"161";
NSString *_rev = #"199";
NSString *_herausgeber = #"SAP";
NSMutableDictionary *toPost = [NSMutableDictionary dictionary];
[toPost setObject:_id forKey:#"_id"];
[toPost setObject:_rev forKey:#"_rev"];
[toPost setObject:_herausgeber forKey:#"Herausgeber"];
NSLog(#"JSON: %#", [toPost JSONRepresentation]);
Gives:
JSON: {"_id":"161","_rev":"199","Herausgeber":"SAP"}