Kartik_Koro
Kartik_Koro

Reputation: 1287

Objective C: Making a json object from dictionary error. Dictionary values can only be strings

I need to get a Json of the form

{
   "_requestName":"login",
   "_ParamNames":[
      "userId",
      "password"
   ],
   "userId":"GFM",
   "password":"a"
}

So I am doing:

NSString *username=self.unTextField.text;
NSString *password=self.pwdTextField.text;
NSArray *params=[NSArray arrayWithObjects:@"userId",@"password", nil];
NSDictionary *dictionary=[NSDictionary dictionaryWithObjectsAndKeys:
                   @"_requestName", @"login",
                   @"_ParamNames", params,
                   @"userId", username,
                   @"password", password,
                   nil];
if (![NSJSONSerialization isValidJSONObject:dictionary]) {
    [self.validationTextField setText:@"Cannot make valid JSON"];
}

I get an error because I'm trying to store the NSArray params as a value in dictionary. The text field does show "Cannot make valid JSON". How do I fix this? The Json MUST be sent in that same format.

Upvotes: 1

Views: 1106

Answers (2)

Alladinian
Alladinian

Reputation: 35616

The problem is that you got keys/objects the other way round (first come the objects then the keys in the method). A better solution would be to just use some literals. Something like this:

NSString *username= @"u";
NSString *password= @"p";

NSDictionary *dictionary = @{
    @"_requestName": @"login",
    @"_ParamNames": @[
        @"userId",
        @"password"
    ],
    @"userId": username,
    @"password": password
};

if (![NSJSONSerialization isValidJSONObject:dictionary]) {
    NSLog(@"Cannot make valid JSON");
} else {
    NSLog(@"Hooray!");
}

Upvotes: 3

Jogendra.Com
Jogendra.Com

Reputation: 6454

Try this working fine .. and also get output in JSON String

 NSString *username=self.unTextField.text;
NSString *password=self.pwdTextField.text;
NSArray *params=[NSArray arrayWithObjects:@"userId",@"password", nil];
NSDictionary *dictionary=[NSDictionary dictionaryWithObjectsAndKeys:
                          @"login", @"_requestName",
                          params,@"_ParamNames",
                         username, @"userId",
                          password, @"password",
                          nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:nil];
NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];

NSLog(@"printing data %@",JSONString);

Upvotes: 0

Related Questions