Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Sending JSONObject from Unity to Node.JS server

Discussion in 'Scripting' started by Davdoc, Apr 10, 2018.

  1. Davdoc

    Davdoc

    Joined:
    Apr 6, 2015
    Posts:
    14
    I am trying to send some data to my Node.JS server using Socket.io. I have a little experience with JSON, but I am no expert. I am using socket.Emit(string ev, JSONObject data), but I have no idea how to form a JSONObject with the data I need to send. I have so far:
    Code (CSharp):
    1.        
    2. void Start () {
    3.  
    4.     latitude = GPS.Instance.latitude.ToString();
    5.     longitude = GPS.Instance.longitude.ToString();
    6.  
    7.     string coordinatesJson = "{ 'latitude': latitude, 'longitude': longitude }";
    8.  
    9.     socket.Emit("send coordinates", coordinatesJson);
    10. }
    11.  
    But this doesn't work because coordinatesJson is a string, of course. Could someone explain how I can create a JSONObject to send this data?
     
  2. TheVahidGR

    TheVahidGR

    Joined:
    Jun 23, 2018
    Posts:
    1
    Change to this:
    Code (CSharp):
    1. socket.Emit("send coordinates", new JSONObject(coordinatesJson));
     
  3. sandeepraj

    sandeepraj

    Joined:
    Mar 22, 2013
    Posts:
    4
    I am getting null in the server if I am using this
     
  4. sandeepraj

    sandeepraj

    Joined:
    Mar 22, 2013
    Posts:
    4
    Is the problem solved
     
  5. sandeepraj

    sandeepraj

    Joined:
    Mar 22, 2013
    Posts:
    4
    Doesn't work for me..... it is sending null
     
  6. Thibault-Potier

    Thibault-Potier

    Joined:
    Apr 10, 2015
    Posts:
    206
    What happen if you Debug.log instead of socket.Emit ? Sure this won't be null ?
     
  7. saswat203

    saswat203

    Joined:
    Apr 16, 2021
    Posts:
    2
    1. [Serializable]
      public class data
      {
      public int data1;

      }
    2. void start(){
    3. data Data = new data();
    4. Data.data1=3;//some value;
    5. string data=JsonUtility.ToJson(Data);
    6. socket.Emit("message", new JSONObject(data));
     
  8. saswat203

    saswat203

    Joined:
    Apr 16, 2021
    Posts:
    2
    this way happend to work for me