0

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"; 
   };
}
warzone_fz
  • 472
  • 1
  • 9
  • 24

3 Answers3

1

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.

dahiya_boy
  • 9,298
  • 1
  • 30
  • 51
0

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

Umair Aamir
  • 1,624
  • 16
  • 26
0

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]
Julian F. Weinert
  • 7,474
  • 7
  • 59
  • 107