Logunath Logunath - 1 year ago 115
iOS Question

Unable to convert to a proper format of NSString from NSArray in iOS

I want to send below JSON parameter in an API call, but the string of contacts array which is used below is confusing and I'm unable to form it in iOS. Below is the working JSON parameter tested in Rest client. How to form a similar pattern of string containing an array of contacts in iOS?

Working JSON Parameter,

"contacts": "[\"5555228243\",\"919677012480\"]",
"phno": "919791871448",
"device": "iphone",
"key": "key",
"name": "Logunath Subramaniyan",
"files": "files"

My code below for conversion,

NSMutableDictionary *reqData = [[NSMutableDictionary alloc]init];
[reqData setObject:[FMCoredDataUtility fetchDetailForKey:kmobileNumber] forKey:@"phno"];
[reqData setObject:[FMCoredDataUtility fetchUserNameForKey:kuserName ]forKey:@"name"];
[reqData setObject:@"iphone" forKey:@"device"];
[reqData setObject:@"key" forKey:@"key"];
[reqData setObject:[self getMobileContacts ] forKey:@"contacts"];
[reqData setObject:@"files" forKey:@"files"];

contactNumbers = [addUtility getContactNumbers];
for ( int i = 0; i < [contactNumbers count]; i++) {
[filteredContacts addObject:[[[contactNumbers objectAtIndex:i] componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""]];
return filteredContacts;

Framed error JSON parameter,

"contacts": [
"phno": "919791871448",
"device": "iphone",
"key": "key",
"name": "Logunath Subramaniyan",
"files": "files"

and error I'm getting in console is,

value __NSCFConstantString *
@"JSON text did not start with array or object and option to allow fragments not set."

Answer Source

Here is a way in which you can convert your ios array to JSON string

    NSArray *contactsArray = [self getMobileContacts ];//This will be your contacts array
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[reqData setObject:jsonString forKey:@"contacts"];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download