I have an issue with my iPhone application or rather Xcode.
I am currently trying to convert a string that i get from Google Translate to a string format that supports cyrillic letters. i tried many String Encodings so far, but none of them seem to work properly.
Here is my code so far:
NSString *word = #"hello";
NSString *urlPath = [NSString stringWithFormat:#"/translate_a/t?client=t&text=%#&langpair=en|ru",word];
NSURL *url = [[NSURL alloc] initWithScheme:#"http" host:#"translate.google.com" path:urlPath];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSURLResponse *response;
NSError *error;
NSData *data;
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"%#", result);
And this is the result on the console:
[
[
[
"ÐÒÉ×ÅÔ",
"hello",
"privet",
""
]
],
[
[
"verb",
[
"ÚÄÏÒÏ×ÁÔØÓÑ",
"Ú×ÁÔØ",
"ÏËÌÉËÁÔØ"
],
[
[
"ÚÄÏÒÏ×ÁÔØÓÑ",
[
"greet",
"hello",
"salute",
"hullo",
"hallo",
"halloa"
],
,
0.0050860695
],
[
"Ú×ÁÔØ",
[
"call",
"invite",
"shout",
"hail",
"hallo",
"hello"
],
,
2.7109536e-05
],
[
"ÏËÌÉËÁÔØ",
[
"hail",
"holler",
"call",
"challenge",
"speak",
"hello"
],
,
2.7109536e-05
]
],
"hello",
2
],
[
"noun",
[
"ÐÒÉ×ÅÔÓÔ×ÉÅ",
"ÐÒÉ×ÅÔÓÔ×ÅÎÎÙÊ ×ÏÚÇÌÁÓ",
"×ÏÚÇÌÁÓ ÕÄÉ×ÌÅÎÉÑ"
],
[
[
"ÐÒÉ×ÅÔÓÔ×ÉÅ",
[
"greeting",
"welcome",
"salute",
"hail",
"salutation",
"hello"
],
,
0.0014801305
],
[
"ÐÒÉ×ÅÔÓÔ×ÅÎÎÙÊ ×ÏÚÇÌÁÓ",
[
"hallo",
"halloa",
"viva",
"hello"
],
,
2.7536449e-05
],
[
"×ÏÚÇÌÁÓ ÕÄÉ×ÌÅÎÉÑ",
[
"hallo",
"halloa",
"hello"
],
,
2.7109536e-05
]
],
"hello",
1
]
],
"en",
,
[
[
"ÐÒÉ×ÅÔ",
[
1
],
true,
false,
1000,
0,
1,
0
]
],
[
[
"hello",
1,
[
[
"ÐÒÉ×ÅÔ",
1000,
true,
false
],
[
"úÄÒÁ×ÓÔ×ÕÊÔÅ",
0,
true,
false
],
[
"Hello",
0,
true,
false
],
[
"úÄÒÁ×ÓÔ×ÕÊ",
0,
true,
false
],
[
"ÈÅÌÌÏ",
0,
true,
false
]
],
[
[
0,
5
]
],
"hello"
]
],
,
[
,
"Hello!",
[
10
],
,
true
],
[
],
2
]
So i hope you get my problem. I want the string to be "привет" and not "ÐÒÉ×ÅÔ".
When i tried to encode the data to other formats i usually get a "(null)" result to my string, like for NSUTF8StringEncoding for example.
"translate.google.com" returns UTF-8 with the following parameters:
NSString *urlPath = [NSString stringWithFormat:#"/translate_a/t?client=t&text=%#&langpair=en|ru&ie=UTF-8&oe=UTF-8",word];
Then
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
should work.
Call this method on the data you're getting instead of initWithData:encoding::
- (NSString*)decodeKOI8R:(NSData*)dataToDecode {
CFStringRef aCFString = CFStringCreateWithCString(NULL, [dataToDecode bytes], kCFStringEncodingKOI8_R);
NSString *decodedString = (__bridge NSString*)aCFString;
return decodedString;
}
Related
Hi I been having huge issues grabbing some data out of this for me quite complex JSON structure.
The problem is that the JSON structure contains some nesting that i can't find out how to handle.
Example of the JSON i get from the database:
{
"hits": {
"totalHits": 3202,
"hits": [{
"id": "70132eb7-2834-458c-900a-da951c95a506",
"versions": [{
"id": 7,
"properties": {
"Status": [
"usable"
],
"created": [
"2015-10-27T14:31:13Z"
],
"Text": [
"Snabbtåg, Järnväg, Höghastighetsjärnväg, "
],
"ConceptDefinitionLong": [
"Enligt Trafikverket saknas en helt entydig och vedertagen definition av höghastigheteståg."
],
"contenttype": [
"Concept"
],
"ConceptProposalUser": [
"[object Object]"
],
"ConceptType": [
"object"
],
"Name": [
"Höghastighetståg"
],
"ConceptNote": null,
"ConceptSeeAlso": null,
"Note": null,
"ConceptName": [
"Höghastighetståg"
],
"updated": [
"2016-02-01T11:37:30Z"
],
"ConceptDefinitionShort": [
"Snabbtåg, Järnväg, Höghastighetsjärnväg, Kollektivtrafik"
],
"ConceptStatus": [
"usable"
]
}
}],
"noVersions": 1
}, {
"id": "4224ccfb-1f0a-9491-727f-f6ab0fc2c951",
"versions": [{
"id": 2,
"properties": {
"Status": [
"usable"
],
"created": [
"2016-01-25T12:03:33Z"
],
"Text": [
"Rosenlundsbadet öppnade 1968 och äventyrsbadet 1991."
],
"ConceptDefinitionLong": [
"Rosenlundsbadet är en badanläggning i Jönköping. "
],
"contenttype": [
"Concept"
],
"ConceptProposalUser": null,
"ConceptType": [
"organisation"
],
"Name": [
"Rosenlundsbadet"
],
"ConceptNote": null,
"ConceptSeeAlso": null,
"Note": null,
"ConceptName": [
"Rosenlundsbadet"
],
"updated": [
"2016-01-25T12:03:38Z"
],
"ConceptDefinitionShort": [
"Simning, Simhopp, Äventyrsbad"
],
"ConceptStatus": [
"usable"
]
}
}],
"noVersions": 1
}
...
My job is to get all the "Name"s from all posts where the "Status" is set to "usable". And store them in my app. But I'm having a hard time getting that info . Im new to JSON and can't handle the structure. This is what i got so far after hours of googling:
NSData *allCoursesData = [[NSData alloc] initWithContentsOfURL:
[NSURL URLWithString:#"http://www.pumba.se/example.json"]];
NSError *error;
NSMutableDictionary *JSONdictionary = [NSJSONSerialization
JSONObjectWithData:allCoursesData
options:kNilOptions
error:&error];
if( error )
{
NSLog(#"%#", [error localizedDescription]);
}
else {
NSArray* entries = [JSONdictionary valueForKeyPath:#"hits.hits"];
NSDictionary *firstItem = [entries objectAtIndex:0];
NSString *id1 = [firstItem objectForKey:#"id"];
NSLog(#"ID: ");
NSLog(id1);
}}
From that code I'm able to get the ID from the first item. But I don't seem to be able to fetch the "name" or check if they are "usable". Have been working with this and trying to solve this for hours but this is above my leauge. I guess the reason to why I can't solve it is cause the data is nested in hits.hits etc. Yet I have to solve this to be able to finish my app. I would be very grateful for some help.
Here is a longer version of the JSON database. The full version contains over 3000 items:
http://jsonviewer.stack.hu/#http://www.pumba.se/example.json
You can use the following code:
NSData *allCoursesData = [[NSData alloc] initWithContentsOfURL:
[NSURL URLWithString:#"http://www.pumba.se/example.json"]];
NSError *error;
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);
}}
Here's the response:
{
"status": true,
"statuscode": 200,
"result": [
{
"name": "ABC",
"date": "2015-01-30",
"documents": [
{
"id": 1,
"name": "doc1",
"status": "complete",
},
{
"id": 2,
"name": "doc2",
"status": "complete",
},
{
"id": 3,
"name": "doc3",
"status": "complete",
}
],
"message": "Hello World",
"status": 3
}
]
}
I want to map and get only all the "document" inside an array keyed "result" and I don't need anything with other objects / mappings. I just need the documents. How can that be done / declared in the response descriptors to automatically match all these documents to my managed object?
Try This :-
NSDictionary *dic=#{
#"status": #true,
#"statuscode":# 200,
#"result": #[
#{
#"name": #"ABC",
#"date": #"2015-01-30",
#"documents": #[
#{
#"id":# 1,
#"name": #"doc1",
#"status": #"complete",
},
#{
#"id":# 2,
#"name": #"doc2",
#"status":# "complete",
},
#{
#"id":# 3,
#"name": #"doc3",
#"status": #"complete",
}
],
#"message": #"Hello World",
#"status":# 3
}
]
};
I am storing your response in NSDictionary and get it by -
[[[dic objectForKey:#"result"] objectAtIndex:0] objectForKey:#"documents"]
change your indexNumber as require !
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; //From Server you will get response data in form of NSData , so the 'responseData' is a type of NSData
NSArray *appDetais = [jsonData objectForKey:#"result"];
NSDictionary *resultJsonData = [appDetais objectAtIndex:0];
NSArray *documentDetailsArray = [jsonData resultJsonData:#"documents"];
for(int i=0;i<[documentDetailsArray count];i++){
NSDictionary *singleDocumentDetail = [documentDetailsArray objectAtIndex:0];
NSLog(#"%#",[singleDocumentDetail objectForKey:#"id"]);
}
You may try this.. :)
I am facing issue with my webserice response. Dictionary keys are auto sorted and i want them as it is
the actual webservice response is :-
[data] => Array
(
[18] => How it works
[22] => Benefits
[23] => Win Free Airtime
[7] => What can I Report?
[10] => Our Goal
[16] => Disclaimer
[8] => FAQ
[13] => Terms & Conditions
[11] => Contact Us
[14] => Feedback / suggestion
)
and it is showing below unfortunately by auto sorting
data = {
10 = "Our Goal";
11 = "Contact Us";
13 = "Terms & Conditions";
14 = "Feedback / suggestion";
16 = Disclaimer;
18 = "How it works";
22 = Benefits;
23 = "Win Free Airtime";
7 = "What can I Report?";
8 = FAQ;
};
I am stuck :( below is my code
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
[spinner stopAnimating];
if ([data length] > 0 && error == nil)
{
//NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary * Dict = [NSDictionary dictionary];
NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *decryptedStr = [[NSData alloc] initWithBase64EncodedString:newStr options:0];
NSDictionary * Dict = [NSJSONSerialization JSONObjectWithData:decryptedStr options:kNilOptions error:nil];
There is no way to do this, because the result is not an array but a dictionary which does not have an order.
You will have to write your own JSON parser and use something else than an NSDictionary to keep the order.
The best way is to change the JSON output use an array:
{
"data": [
{
"key": 10,
"value": "Our Goal"
},
{
"key": 11,
"value": "Contact Us"
},
{
"key": 13,
"value": "Terms & Conditions"
},
{
"key": 14,
"value": "Feedback / suggestion"
},
{
"key": 16,
"value": "Disclaimer"
},
{
"key": 18,
"value": "How it works"
},
{
"key": 22,
"value": "Benefits"
},
{
"key": 23,
"value": "Win Free Airtime"
},
{
"key": 7,
"value": "What can I Report?"
},
{
"key": 8,
"value": "FAQ"
}
]
}
My code at follow
CCLOG("info: %s",infoStr.c_str());
const char * buf=infoStr.c_str();
cocos2d::extension::Json* mJs = cocos2d::extension::Json_create(buf);
cocos2d::extension::Json* item = Json_getItem(mJs,"results");
cocos2d::extension::Json* array1 = Json_getItemAt (item, 0);
cocos2d::extension::Json* itemNode = Json_getItem(array1,"version");
float floatValue = itemNode->valuefloat;
CCLOG("floatValue: %f",floatValue);
The result of CCLOG("info: %s",infoStr.c_str()); is at follow:
{
"resultCount": 1,
"results": [
{
"kind": "software",
"features": [],
"supportedDevices": [
"iPhone4S",
"iPadWifi",
"iPadThirdGen4G",
"iPhone5",
"iPadMini4G",
"iPadFourthGen4G",
"iPodTouchThirdGen",
"iPadThirdGen",
"iPad3G",
"iPhone4",
"iPodTouchourthGen",
"iPodTouchFifthGen",
"iPhone-3GS",
"iPad2Wifi",
"iPhone5c",
"iPad23G",
"iPhone5s",
"iPadFourthGen",
"iPadMini"
],
"isGameCenterEnabled": false,
"screenshotUrls": [
"http://a5.mzstatic.com/us/r30/Purple/v4/52/c0/e5/52c0e504-3e37-80a8-f17a-0b49bff6e63b/screen1136x1136.jpeg",
"http://a4.mzstatic.com/us/r30/Purple6/v4/b6/8d/50/b68d500a-b84a-44fe-7fac-a055aa49e2ee/screen1136x1136.jpeg",
"http://a5.mzstatic.com/us/r30/Purple4/v4/30/80/ab/3080ab26-fa55-a69b-480d-a57c803f3b81/screen1136x1136.jpeg"
],
"ipadScreenshotUrls": [],
"artworkUrl60": "http://a288.phobos.apple.com/us/r30/Purple6/v4/e6/89/56/e689561d-2bbc-8769-4325-b2acd91e0cf9/AppIcon57x57.png",
"artworkUrl512": "http://a1062.phobos.apple.com/us/r30/Purple4/v4/1d/8c/2c/1d8c2c76-d441-4d3b-d43c-48e6f7aa98ad/mzl.oympcnqz.png",
"artistViewUrl": "https://itunes.apple.com/us/artist/wei-gao/id777399907?uo=4",
"artistId": 777399907,
"artistName": "wei gao",
"price": 0,
"version": "1.0",
"description": "description",
"currency": "USD",
"genres": [
"Photo & Video",
"Entertainment"
],
"genreIds": [
"6008",
"6016"
],
"releaseDate": "2014-01-02T23:19:32Z",
"sellerName": "w",
"bundleId": "D.IMyPhotos",
"trackId": 77,
"trackName": "ff",
"primaryGenreName": "Photo & Video",
"primaryGenreId": 6008,
"formattedPrice": "Free",
"wrapperType": "software",
"trackCensoredName": "ff",
"languageCodesISO2A": [
"EN"
],
"fileSizeBytes": "14",
"sellerUrl": "http://wwww",
"contentAdvisoryRating": "4+",
"artworkUrl100": "http://a1062.phobos.apple.com/us/r30/Purple4/v4/1d/8c/2c/1d8c2c76-d441-4d3b-d43c-48e6f7aa98ad/mzl.oympcnqz.png",
"trackViewUrl": "https://itunes.apple.com/us/app",
"trackContentRating": "4+"
}
]
}
I get Json* mJs always NULL.I think the string of json is right.I used google but can't get the answer.
Do i use Json_create in the wrong way? Or other reason? A lot of thank!
That's the content...
[
{
"id": "",
"title": "",
"website": "",
"categories": [
{
"id": "",
"label": ""
}
],
"updated":
},
{
"id": "",
"title": "",
"website": "",
"categories": [
{
"id": "",
"label": ""
}
],
"updated":
}
]
How can I insert every feed source in one array?
NSDictionary *results = [string JSONValue];
NSArray *subs = [results valueForKey:#"KEY"];
Which key I must insert?
THanks
as I can see your structure, you will get out of this JSON-String
NSArray:
[
NSDictionary:
{
NSString: "id",
NSString: "title",
NSString: "website",
NSArray: "categories":
[
NSDictionary:
{
NSString: "id",
NSString: "label"
}
],
NSNumber: "updated"
},
NSDictionary:
{
...
}
]
So you have already an array of "Feeds" at root and you have to itterate them with their index in the array with. For first id i.e. [[myJsonStructure objectAtIndex:0] objectForKey:#"id"];