generating JSON from NSMutableDictionary - ios

I am new to Objective-C and iOS development and am trying to write a method for generating a JSON string but when i NSLog this i get a bunch of hexcodes (i am guessing they are pointer adresses) can someone look at this method and tell me what i am doing wrong..
-(NSData *)generateInputJSON
{
NSError* error = nil;
NSString* region = [[NSLocale currentLocale]localeIdentifier];
NSString* language = [[NSLocale preferredLanguages]objectAtIndex:0];
NSMutableDictionary* properties = [NSMutableDictionary dictionaryWithObjectsAndKeys:
_sphereODNumber,#"sphereOD",
_sphereOSNumber,#"sphereOS",
_cylinderODNumber,#"cylinderOD",
_cylinderOSNumber,#"cylinderOS",
_visionCorrection,#"visionCorrection",
region,#"region",
language,#"language",
nil];
if([_visionCorrection isEqualToString:#"multiFocal"] ||
[_visionCorrection isEqualToString: #"progressive"])
{
[properties setValue:_addODNumber forKey:#"addOD"];
[properties setValue:_addOSNumber forKey:#"addOS"];
}
if([_visionCorrection isEqualToString: #"progressive"])
{
[properties setValue:_fittingHeightNumber forKeyPath:#"fittingHeight"];
}
NSData* inputJSON = [NSJSONSerialization dataWithJSONObject:properties options:NSJSONWritingPrettyPrinted error:&error];
return inputJSON;
}
my Log returns:
<7b0a2020 226c616e 67756167 6522203a 2022656e 222c0a20 20227669 73696f6e 436f7272 65637469 6f6e2220 3a202270 726f6772 65737369 7665222c 0a202022 6164644f 4422203a 20342e35 2c0a2020 22616464 4f532220 3a20342e 352c0a20 20227370 68657265 4f532220 3a20342e 352c0a20 20227265 67696f6e 22203a20 22656e5f 5553222c 0a202022 63796c69 6e646572 4f532220 3a20342e 352c0a20 20226669 7474696e 67486569 67687422 203a2031 372c0a20 20227370 68657265 4f442220 3a20342e 352c0a20 20226379 6c696e64 65724f44 22203a20 342e350a 7d>

What you're seeing is a description of the NSData object, which is just the the bytes in the data in hex. If you were to (say) write that data to a file and open the file with a text editor you'd actually see the string you want. Since you want to return a string from your function, you can convert the NSData to a string like so:
return [[NSString alloc] initWithData:inputJSON encoding:NSUTF8StringEncoding];
Remember to autorelease that if you're in non-ARC code. You should also change the return type of your method from NSData* to NSString* if you're going to return a string.

Convert the data into an NSString like so
NSString *string = [[NSString alloc]initWithData:inputJSON encoding:NSUTF8StringEncoding];
then just print it with NSLog
NSLog(#"%#", string);

Related

Converting NSString to JSON with NSJSONSerialization is not working

I have this function:
- (void)checkLogin:(NSString *)pLogin andPassword:(NSString*) pPassword {
//Create the data object.
NSMutableDictionary *tLoginAndPasword = [NSMutableDictionary dictionaryWithObjectsAndKeys:pLogin,#"Login",pPassword,#"Password", nil];
NSMutableDictionary *tData = [NSMutableDictionary dictionaryWithObjectsAndKeys:[_Util serializeDictionary:tLoginAndPasword],#"Data", nil];
//Call the login method.
NSData *tResponse = [_Util getLogin:tData];
if (tResponse != Nil) {
_oLabelErrorLogin.hidden = YES;
[_Util setUser:pLogin andPassword:pPassword];
NSMutableDictionary *tJSONResponse =[NSJSONSerialization JSONObjectWithData:tResponse options:kNilOptions error:nil];
NSString *tPayload = [tJSONResponse objectForKey:#"Payload"];
if([[tJSONResponse objectForKey:#"StatusCode"] isEqual: #"424"]) {
//Set global values.
NSData *tPayloadData = [tPayload dataUsingEncoding:NSUTF8StringEncoding];
if ([NSJSONSerialization isValidJSONObject:tPayloadData]) {
_Payload = [NSJSONSerialization JSONObjectWithData:tPayloadData options:kNilOptions error:nil];
_RowCount = _Payload.count;
} else {
NSLog(#"JSON Wrong String %#",tPayload);
}
} else if([[tJSONResponse objectForKey:#"StatusCode"] isEqual: #"200"]){
_Payload = Nil;
}
} else {
//Set global values.
_Payload = Nil;
_oLabelErrorLogin.hidden = NO;
//Clear login data.
_oLogin.text = #"";
_oPassword.text = #"";
[_Util setUser:#"" andPassword:#""];
}
}
The JSON response looks like this:
{
"Payload": "{\"UserName\":\"Marco Uzcátegui\",\"Clients\":[{\"UserProfileId\":4,\"ProfileName\":\"Platform Administrator\",\"ClientName\":\"Smart Hotel Platform\",\"InSession\":true},{\"UserProfileId\":5,\"ProfileName\":\"Administrator\",\"ClientName\":\"La Moncloa de San Lázaro\",\"InSession\":false},{\"UserProfileId\":6,\"ProfileName\":\"Administrator\",\"ClientName\":\"Jardín Tecina\",\"InSession\":false}]}",
"StatusCode": "424",
"StatusDescription": null
}
As you can see, I have a escaped string inside "Payload" that is a correct JSON, so I want to generate another NSMutableDictionary with that string, so I'm doing this:
NSData *tPayloadData = [tPayload dataUsingEncoding:NSUTF8StringEncoding];
if ([NSJSONSerialization isValidJSONObject:tPayloadData]) {
_Payload = [NSJSONSerialization JSONObjectWithData:tPayloadData options:kNilOptions error:nil];
_RowCount = _Payload.count;
} else {
NSLog(#"JSON Wrong String %#",tPayload);
}
So I'm creating an NSData from the NSString and asking if is valid, it always returns false.
I have tried to replace the "\" from the string and is not working.
[tPayload stringByReplacingOccurrencesOfString:#"\\\"" withString:#""]
I have tried to create a NSMutableDictionary with the string, but the result is not a dictionary.
NSMutableDictionary *tPayload = [tJSONResponse objectForKey:#"Payload"];
I'm kind of lost here.
Any help will be appreciated.
Regards.
The issue is this line
[NSJSONSerialization isValidJSONObject:tPayloadData]
From the documentation of isValidJSONObject
Returns a Boolean value that indicates whether a given object can be
converted to JSON data.
given object means an NSArray or NSDictionary but not NSData
Remove that check and implement the error parameter in JSONObjectWithDataoptions:error:
The method NSJSONSerialization.isValidJSONObject: checks if an object (e.g. a NSDictonary or NSArray instance) can be converted to JSON. It doesn't check if a NSData instance can be converted from JSON. For NSData, it will always return false.
So just call NSJSONSerialization.JSONObjectWithData:options: and check the result instead.

Worklight Adapter Call in IOS Native Passing JSON Parameter

When using JSON.parse(parameter-value) in JavaScript, the adapter invocation is working correctly, however when doing similarly in a native iOS app, it is failing with the following error.
Javascript Adapter Call:
var invocationData = {
adapter : 'TEST_ADAP',
procedure : 'PROC1',
parameters : [JSON.parse(A)],
};
Native Call:
json= // some json value will be come
MyConnect *connectListener = [[MyConnect alloc] initWithController:self];
[[WLClient sharedInstance] wlConnectWithDelegate:connectListener];
WLProcedureInvocationData *myInvocationData = [[WLProcedureInvocationData alloc] initWithAdapterName:#"TEST" procedureName:#"test"];
myInvocationData.parameters = [NSArray arrayWithObjects:json, nil];
for (NSString *str in myInvocationData.parameters) {
NSLog(#"values of account test %#",str);
}
PasswardPage *invokeListener = [[PasswardPage alloc] initWithController:self];
[[WLClient sharedInstance] invokeProcedure:myInvocationData withDelegate:invokeListener];
Your line
myInvocationData.parameters = [NSArray arrayWithObjects:json, nil];
is almost right.
The parameters property should be an NSArray (as you did) but the array must be made of string values - NOT a JSON object.
myInvocationData.parameters = [NSArray arrayWithObjects:#"myValue1", #"myValue2", #"myValue3", nil];
If the data you received is not in this format, you need to first convert it to this format. This is out of the scope of this question.
If you are not sure how to convert your existing format into a valid NSArray, please open a new question (tagged with Objective-C, not worklight).
We can pass JSON as NSString in iOS Native code to invoke adapter
Example
//Created Dictionary
NSMutablec *dict = [[NSMutableDictionary alloc]init];
[dict setObject:#"xyz" forKey:#"Name"];
[dict setObject:#"iOS" forKey:#"Platform"];
//Convert it to JSON Data
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:nil
error:&error];
//JSON Data To NSString
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
WLProcedureInvocationData * invocationData = [[WLProcedureInvocationData alloc] initWithAdapterName:#"XYZAdapter" procedureName:#"FunctionXYZ"];
//Passing jsonString (NSString Created out of JSON Data) as array to set Parameters.
[invocationData setParameters:[NSArray arrayWithObject:jsonString]];
[[WLClient sharedInstance] invokeProcedure:invocationData withDelegate:self];

how to remove the \ character

I have a string with the following information:
\"[{\"CodRTA\":\"1\",\"MenssRTA\":\"messaje error\",\"Resp\":\"\"}]\"
and I need to delete the character \ I'm trying to remove as follows, but the character is using the system and leaves close the line of code
NSString *filtered = [[[restConnection stringData] componentsSeparatedByString:#"\"] componentsJoinedByString:#""];
NSLog(#"filtrado: %#", filtered);
the error is
Expected ']' in this part : componentsSeparatedByString:#"\"]
Its looks like JSON data, instead interfering into JSON, just convert JSON string to NSData and then into NSDictionary or NSArray
NSString *jsonString = #"[{\"CodRTA\":\"1\",\"MenssRTA\":\"messaje error\",\"Resp\":\"\"}]";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray *array = [NSArray arrayWithArray:json];
Now if you do following NSLog statement
NSLog(#"%#",[[json firstObject] objectForKey:#"CodRTA"]);
Result would be another NSDictionary.
{
CodRTA = 1;
MenssRTA = messaje error;
Resp = "";
}
Btw, I formatted your JSON response, its look like this,
Someting like that
string = [string stringByReplacingOccurrencesOfString:#"\\" withString:#""];
use this code
NSString *str=#"[{\"CodRTA\":\"1\",\"MenssRTA\":\"messaje error\",\"Resp\":\"\"}]";
NSString *filtered = [[str componentsSeparatedByString:#"\\"] componentsJoinedByString:#""];
NSLog(#"filtrado: %#", filtered);

What is the best method to break this into usable strings

Whats is the best way to parse this out?
String:
UMversion=2.9&UMstatus=Approved&UMauthCode=152058&UMrefNum=59567592&UMavsResult=Address%3A%20Match%20%26%205%20Digit%20Zip%3A%20Match&UMavsResultCode=YYY&UMcvv2Result=Match&UMcvv2ResultCode=M&UMresult=A&UMvpasResultCode=&UMerror=Approved&UMerrorcode=00000&UMcustnum=&UMbatch=1&UMbatchRefNum=91016&UMisDuplicate=N&UMconvertedAmount=&UMconvertedAmountCurrency=840&UMconversionRate=&UMcustReceiptResult=No%20Receipt%20Sent&UMprocRefNum=&UMcardLevelResult=A&UMauthAmount=10&UMfiller=filled
I get this back from the web service as one big long string. Each of the variables are listed then they have a = sign then what I need to populate the variable with.
I need to get all of this data into variables to check them.
So, how should I go about breaking it down.
Use this kind of code:
NSArray* components = [veryLongString componentsSeparatedByString:#"&"]; // array of strings like "x=y"
NSMutableDictionary* parsedResult = [NSMutableDictionary new];
for (NSString* keyValuePair in components) {
NSArray* keyAndValue = [keyValuePair componentsSeparatedByString:#"="];
NSString* key = keyAndValue[0];
NSString* value = (keyAndValue.count>1) ? keyAndValue[1] : nil;
// remove percent escapes in case we have URL-encoded characters in the value like '%20' and the like
parsedResult[key] = [value stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ?: [NSNull null];
}
NSLog(#"dictionary of parameters: %#", parsedResult);
You will end up with a dictionary containing the keys and values extracted from your string.
NSString* firstPass = [sourceString stringByReplacingOccurrencesOfString:#"&" withString:#"\",\""];
NSString* secondPass = [firstPass stringByReplacingOccurrencesOfString:#"=" withString:#"\":\""];
NSString* grandFinale = [NSString stringWithFormat:#"{\"%#\"}"];
NSData* jsonSource = [grandFinale dataUsingEncoding:NSUTF8Encoding];
NSError* error = nil;
NSDictionary* theBiggie = [NSJSONSerialization JSONObjectWithData:jsonSource options:0 error:&error];
I think NSJSONSerialization will automagically fix up the percent encoding. If not, run grandFinale through stringByRemovingPercentEncoding.

iOS parsing img tag found in JSON

I am trying to parse the file location from the following so that image can be displayed. How do I do it?
[
{
"title":"testing barcode display",
"body":"lets see if it renders \r\n\r\n",
"author":"1",
"created":"1373490143",
"nid":"5",
"Barcode":"<img class=\"barcode\" typeof=\"foaf:Image\" src=\"http://mysite.com/sites/default/files/barcodes/95b2d526b0a8f3860e7309ba59b7ca11QRCODE.png\" alt=\"blahimage\" title=\"blahimage\" />"
}
]
I have a table view which displays the title tag. I need to display the entire content in the detail view. I can do everything except the Barcode tag. Please advise.
If it should be done, parse the xml
NSString *xmlString = #"<img class=\"barcode\" typeof=\"foaf:Image\" src=\"http://mysite.com/sites/default/files/barcodes/95b2d526b0a8f3860e7309ba59b7ca11QRCODE.png\" alt=\"blahimage\" title=\"blahimage\" />";
GDataXMLElement *xmlElement = [[GDataXMLElement alloc]initWithXMLString:xmlString error:nil];
NSArray *attributes = [xmlElement attributes];
[attributes enumerateObjectsUsingBlock:^(GDataXMLNode * node, NSUInteger idx, BOOL *stop) {
NSLog(#"%# : %#",node.name,node.stringValue);
}];
OR
NSString *class = [[xmlElement attributeForName:#"class"] stringValue];
NSString *typeOf = [[xmlElement attributeForName:#"typeof"] stringValue];
NSString *src = [[xmlElement attributeForName:#"src"] stringValue];
NSString *alt = [[xmlElement attributeForName:#"alt"] stringValue];
NSString *title = [[xmlElement attributeForName:#"title"] stringValue];
Use json-framework or something similar.
If you do decide to use json-framework, here's how you would parse a JSON string into an NSDictionary:
SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease];
// assuming jsonString is your JSON string...
NSDictionary* myDict = [parser objectWithString:jsonString];
// now you can grab data out of the dictionary using objectForKey or another dictionary method
You have to convert json string in nsdictionary, so try this
SBJSON *json = [[SBJSON new] autorelease];
NSError *error;
NSDictionary *dict = [json objectWithString:YOUR_JSON_STRING error:&error];
add user this dictionary to display details in tableView

Resources