-2

my api expects to receive JSON data in below form

{
  "user_contacts" : [
    {
      "friend_list" : "+928885555512",
      "user_id" : "1"
    },
    {
      "friend_list" : "+925555648583",
      "user_id" : "1"
    },
    {
      "friend_list" : "+925555228243",
      "user_id" : "1"
    }
  ]
}

i have created this data through array of dictionaries and its working fine and it is stores in Data type Variable. As alamofire requires [String: Any] type of parameter so i have to convert that data into desired format so i tried this:

let my_dict = try JSONSerialization.jsonObject(with: jsonData!, options: []) as! [String: Any]

but when print this my_dict before call alamofire. it seems that it is not a correct json see below... with something like that: __NSArrayI 0x618000271dc0>

["user_contacts": <__NSArrayI 0x618000271dc0>(
{
    "friend_list" = "+928885555512";
    "user_id" = "1";
},
{
    "friend_list" = "+925555228243";
    "user_id" = "1";
},
{
    "friend_list" = "+925554787672";
    "user_id" = "1";
}
)
]

So how can i make this correct json form? what i am doing wrong?

Updated:

let updated_User_No :[String:Any]=["friend_list": self.new_convert_telephone_no,"user_id": user_no];

                user_outer_arrary.append(updated_User_No);

                user_inner_array=["user_contacts": user_outer_arrary]

it Should be look like this:

{
  "user_contacts" : [
    {
      "friend_list" : "+928885555512",
      "user_id" : "1"
    },
    {
      "friend_list" : "+925555648583",
      "user_id" : "1"
    }
  ]
}
catalyst
  • 1
  • 6
  • You do have a serialized JSON Object in Swift/iOS. I think Alamofire uses a different data structure;-) You need to convert the ios native data structure to the expected string data structure of alamofire: This might help you: http://stackoverflow.com/questions/6368867/generate-json-string-from-nsdictionary-in-ios – Lepidopteron May 04 '17 at 07:25
  • thnaks! but it does'nt solve my problem. i already hvae json data but it is type Data Variable. is there any way to store json data in dictionary in [string: any] type. – catalyst May 04 '17 at 07:53
  • user_inner_array is this array ? – KKRocks May 04 '17 at 09:16
  • @catalyst check my answer. – KKRocks May 04 '17 at 11:01

2 Answers2

1

Try this :

Create Structure

let users = ["" : ["user_contacts": [["friend_list":"user_id"],["friend_list3":"user_id3"]]]]

Create Json Object

let json = try JSONSerialization.jsonObject(with: data!, options:.prettyPrinted) as? [String : AnyObject]
KKRocks
  • 8,222
  • 1
  • 18
  • 84
  • @KKRocls : not works. now it prints: Optional([AnyHashable("user_contacts"): <__NSArrayI 0x610000274600>( – catalyst May 04 '17 at 08:36
1

Perform JSONSerialization as below:

let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? Dictionary<AnyHashable, Any>
Sakir Sherasiya
  • 1,562
  • 1
  • 17
  • 31