Logunath
Logunath

Reputation: 477

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"];

-(NSArray*)getMobileContacts{
    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": [
    "5555228243",
    "5554787672",
    "4085555270",
    "4085553514",
    "5556106679",
    "5557664823",
    "7075551854",
    "8885555512",
    "8885551212",
    "5555648583",
    "4155553695",
    "919677012480"
  ],
  "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." 0x000000010cf2ed50

Upvotes: 0

Views: 71

Answers (1)

Harsh
Harsh

Reputation: 2908

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"];

Upvotes: 1

Related Questions