iPhone:Issues when formatting json for server request - iphone

I need to make the json params like below.
Final output should be,
{"submissionTime":"\/Date(1331549630849)\/",
"statusId":"0",
"answers":[{"answer":"Yes","qid":167},{"answer":"Hello","qid":168}],
"participantId":"16369",
"token":"t_ikHOXVjlcsSb9Tfdn5RaO54JGQobHodUD5881SKevxy63jwLxe8ZPQvXYss4pR"}
I am trying to make this format. I got the time, statusid, participantid and token. Its fine. But, i am facing problem when making "answers" array.
I use the below code for making the answers json format like below.
NSArray *answerkeys = [NSArray arrayWithObjects:#"answer", #"qid",nil];
NSString *qID = [NSString stringWithFormat:#"%d", [questionidArray objectAtIndex:i] ]; // for loop
NSArray *objectkeys = [NSArray arrayWithObjects:value, qID,nil];
NSString *answerjsonRequest = [pSr makeJSONObject:objectkeys :answerkeys];
answerjsonRequest = [(NSString *)answerjsonRequest stringByReplacingOccurrencesOfString:#"\n" withString:#""];
[textvaluesArray addObject:[NSString stringWithFormat:#"%#", answerjsonRequest]];
and the output is like below.
(
"{ \"answer\" : \"Hello\", \"qid\" : \"220421824\"}",
"{ \"answer\" : \"How are you\", \"qid\" : \"115781136\"}"
)
But, when i am adding all in one in the final output like below,
NSString *jsonRequest = [pSr makeJSONObject:[NSArray arrayWithObjects: participantID, (NULL!=textvaluesArray)?textvaluesArray:#"0", [NSString stringWithFormat:#"%d", statusID], subTime, [appDelegate getSessionToken], nil] :[NSArray arrayWithObjects:#"participantId", #"answers", #"statusId", #"submissionTime", #"token", nil] ];
The final json result is this.
{
"submissionTime" : "\/Date(1331566698)\/",
"token" : "t_hvYoxifLQhxEKfyw1CAgVtgOfA3DjeB9jZ3Laitlyk9fFdLNjJ4Cmv6K8s58iN",
"participantId" : "16371",
"answers" : [
"{ \"answer\" : \"Hello\", \"qid\" : \"220421824\"}",
"{ \"answer\" : \"Hello\", \"qid\" : \"115781136\"}"
],
"statusId" : "0"
}
BUT, this is NOT the one what i want. My expected JSON output is top above mentioned. I tried many ways, but couldn't achieve this. Could someone helping me on this to resolve to get the exact JSON output?
Thank you!

I ran into this issue as well, and created a quick category to take care of the problem.
#interface NSString (ReplaceForJSON)
- (NSString*)replaceEscapedQuotes;
#end
#implementation NSString (ReplaceForJSON)
- (NSString*)replaceEscapedQuotes
{
NSString* returnVal = [self stringByReplacingOccurrencesOfString:#"\\\"" withString:#"\""];
returnVal = [returnVal stringByReplacingOccurrencesOfString:#"\"{" withString:#"{"];
returnVal = [returnVal stringByReplacingOccurrencesOfString:#"}\"" withString:#"}"];
return returnVal;
}
#end

Related

Get specific value from NSMutableArray

I'm parsing an XML and saving result to NSMutableArray. When I do NSLog,
NSLog(#"Data : %#",_data);
I'm getting
Data : (
{
SessionToken = 9e72dd029e0e8268380b919356881935;
}
)
I only want 9e72dd029e0e8268380b919356881935 from the array. What is the best solution to achieve this?
EDIT : There will be only one SessionToken at a time.
You can try this code :
for (NSDictionary *data1 in _data) {
NSlog("session token %#",[data1 objectForKey:#"SessionToken"]);//Other wise add into another array which contain session token.. only..
}
Since there will be only one session at a time.
NSDictionary *session = [_data lastObject];
NSString *sessionToken = session[#"SessionToken"];
OR with literals
NSString *sessionToken = _data[0][#"SessionToken"];
if ([_data count]) {
NSDictionary *dic = [_data objectAtIndex:0];
NSLog(#"Data : %#",[dic objectForKey:#"SessionToken"]);
}
for (NSDictionary *data1 in _data) {
NSlog("session token %#",[data1 valueForKey:#"SessionToken"]);
}

How to get data from JSON data

I have JSON like this:
[{"ID" : "351", "Name" : "Cam123 ", "camIP" : "xxx.xxx.xxx.xxx",
"Username" : "admin", "Password" : "damin", "isSupportPin" : "1" },
{"ID" : "352", "Name" : "Cam122 ", "camIP" : "xxx.xxx.xxx.xxx",
"Username" : "admin", "Password" : "damin", "isSupportPin" : "0" }
]
I want to get isSupportPin with result: 1 or 0.
if (x == 1)
{
mybutton.enabled = TRUE;
}
else
{
mybutton.enabled = FALSE;
}
How I can do it?
Assuming you have an NSData object with this data in it:
// Your JSON is an array, so I'm assuming you already know
// this and know which element you need. For the purpose
// of this example, we'll assume you want the first element
NSData* jsonData = /* assume this is your data from somewhere */
NSError* error = nil;
NSArray* array = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if( !array ) {
// there was an error with the structure of the JSON data...
}
if( [array count] > 0 ) {
// we got our data in Foundation classes now...
NSDictionary* elementData = array[0]; // pick the correct element
// Now, extract the 'isSupportPin' attribute
NSNumber* isSupportPin = elementData[#"isSupportPin"];
// Enable the button per this item
[mybutton setEnabled:[isSupportPin boolValue]];
} else {
// Valid JSON data, but no elements... do something useful
}
The above example code snippet assumes you know which element you want to read (I guess these are user lines or something) and that you know what the JSON attribute names are (e.g., if isSupportPin isn't actually defined in the JSON object returned in that array, it will simply return nil, which will always evaluate to NO when you send it -boolValue).
Finally, the above code is written for ARC and requires Xcode 4.5 or Clang 4.1 and a deployment target of iOS 5.0. If you're not using ARC, building with a legacy version of Xcode, or targeting something earlier than 5.0, you'll have to adjust the code.
Here what you have is an NSArray of NSDictionarys. So using SBJSON library you could do as following
SBJsonParser *parser = [SBJsonParser alloc] init];
NSArray *data = [parser objectFromString:youJson];
for (NSDictionary *d in data)
{
NSString *value = [d objectForKey:#"Name"];
}
The library can be found at http://stig.github.com/json-framework/
Follow the below link that my help you.
http://www.xprogress.com/post-44-how-to-parse-json-files-on-iphone-in-objective-c-into-nsarray-and-nsdictionary/
If you want to get data or Dictionary fron JSONData then use bellow code..
NSString *responseString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
NSArray *resultsArray = [responseString JSONValue];
for(NSDictionary *item in resultsArray)
{
NSDictionary *project = [item objectForKey:#"result"];//use your key name insted of result
NSLog(#"%#",project);
}
and also download JSON Library and tutorial from below link...
http://mobileorchard.com/tutorial-json-over-http-on-the-iphone/

iPhone: Issue when adding json NSString into NSMutableArray

I am setting a json output like below. It is a NSString.
MyNSString = {
title = FirstOne;
titleno = 95;
}
MyNSString = {
title = SecondOne;
titleno = 96;
}
I have to add like the above json multiple strings into an NSArray (or) NSMutableArray. I am trying to add in NSMutableArray. When i want to add like the above json string into an NSMutableArray, the output comes like below, with \n .
[outNSMutableArray addObject:[NSString stringWithFormat:#"%#", MyNSString] ];
(
"{\n \"title\" : \"FirstOne\",\n \"titleno\" : \"95\"\n}",
"{\n \"title\" : \"SecondOne\",\n \"titleno\" : \"96\"\n}"
)
I want this to be like below, without "\n \" added.
[ {"title":"FirstOne","titleno":95},{"title":"SecondOne","titleno":96}]
How can i correct this? Could someone help?
NSString* string = [myJSONString stringByReplacingOccurencesOfString: #"\n" withString: #""];
EDIT:
So you have this:
[outNSMutableArray addObject:[NSString stringWithFormat:#"%#", MyNSString] ];
Change it to this:
NSString* str = [MyNSString stringByReplacingOccurencesOfString: #"\n" withString: #""];
[outNSMutableArray addObject:[NSString stringWithFormat:#"%#", str] ];

jsonkit decoding

hi im using jsonkit to deserialize json kit data. this is the code i use.
NSString * strResult = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
nslog(#"strresult");
NSDictionary *deserializedData = [strResult objectFromJSONString];
nslog(#"result");
o/p:
"data": {
"translations": [
{
"translatedText": "hello"
}
]
}
}
result {
data = {
translations = (
{
translatedText = "\U091c\U093e\U0928\U093e";
}
);
};
}
what is the problem????? thanks in advance
Try to use http://code.google.com/p/json-framework/.
Your code will look like this. And you need to include #import "JSON.h"
NSString * strResult = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"strresult");
NSDictionary *deserializedData = [strResult JSONValue];
I think the problem is from string encoding.

iPhone - parsing a plist file into an array without success

I try to put a plist file content into an array using this functions :
NSString *path = [[NSBundle mainBundle] pathForResource:#"DataFile" ofType:#"plist"];
self.contentData = [NSArray arrayWithContentsOfFile:path];
But self.contentData keeps being null...
I don't understand why. I used the same code than the one shown in the Apple "PageControl" sample project (See here), using also a pList file with the same structure (list of Dictionary items with 2 strings inside).
path is filled with : /var/Mobile/Applications/somehexvalues/MyApp.app/DataFile.plist
How could I know what is going wrong ?
NSLog(#"%#", [NSDictionary dictionaryWithContentsOfFile:path]); gives :
"Item 0" = {
imageKey = "hearts.png";
nameKey = Hearts;
};
"Item 1" = {
imageKey = "leef.png";
nameKey = Leef;
};
"Item 2" = {
imageKey = "round.png";
nameKey = Round;
};
Your PLIST has an NSDitionary instead of an NSArray, that is why you get null. If you try to load an NSArray into a NSDcitionary, you will get null as well.