warzone_fz
warzone_fz

Reputation: 482

How to send JSON with dictionary and array in iOS(Objective c )?

I am trying to send a JSON to websocket. the required format is coming up with commas whereas when i add item to dictionary then its creating a semi-colon.

Required Format :

{"key":"driver_location_updates","driverID":40,"coordinates":[25.22632,55.2844576]}

Format I created :

"driver_location_updates" =    
   {
       coordinates = ( "24.96046731716484","67.05977029173361"); 
       driverID = 16;
       key = "driver_location_updates"; 
   };
}

Upvotes: 0

Views: 417

Answers (3)

Julian F. Weinert
Julian F. Weinert

Reputation: 7560

From the format I guess you have used [NSString stringWithFormat:@"%@"] or got the "JSON" from a call to -[NSDictionary description].

This does not create JSON, but a general, human readable notation of the data structure. It kind of looks like JSON and I had the exact same issue many years back :)

Use NSJSONSerialization to get real JSON:

NSData *JSONData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 &error];

or directly write to a stream

[NSJSONSerialization writeJSONObject:dictionary toStream:writeStream options:0 error:&error]

Upvotes: 0

dahiya_boy
dahiya_boy

Reputation: 9503

As you said in comments

  1. key is not with inverted commas.

  2. There is Semi-colon after end of every value

  3. Round Bracket in coordinates

Explanation :

  1. Because your key is single worded so it is assumable that it is string (as there is chars not integer). Try by keeping key as two words like key mine or key_2

Output => enter image description here

  1. Because after every key in dictionary there is semi-colon. (x-code syntax for dictionanary).

  2. Because array in console is represented in (...) where as dictionary will be represented in {...}.

Now, more over if you observe there is = in Dictionary but in json there is :. It is just because array dictionary notation is different from json.

By considering the above points, it makes you clear that both are same.

Upvotes: 1

Umair Aamir
Umair Aamir

Reputation: 1644

You should use JSONSerialization to convert dictionary to json I guess.

let dictionary: [String: Any] = ["key":"driver_location_updates", "driverID": 40, "coordinates": [25.22632,55.2844576]]

let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: [])
let jsonString = String(data: jsonData!, encoding: .utf8)
print(jsonString)

I hope you know how to convert the answer to Objective C

Upvotes: 0

Related Questions