pusher / pusher-websocket-unity

Pusher Channels Unity Client Library
MIT License
27 stars 20 forks source link

Accessing JSON data in an event #46

Closed shealan closed 1 year ago

shealan commented 1 year ago

There doesn't seem to be a clear way of accessing the JSON payload of an event documented in the repository. This seems odd as it's such a classic use case.

There are several mentions of "overload methods" but I would really appreciate a code example. I have tried some snippets from other issues posted here with no luck.

    private void PusherOnConnected(object sender)
    {
        Debug.Log("Connected");

        _channel.Bind("my-event", (dynamic data) =>
        {
            Debug.Log("Here's the data: " + data.ToString());
        });
    }

image

This is what I see in my Unity console when sending through an event via the Pusher debug panel.

Here's the data: { event = my-event, data = {"foo": "bar"}, channel = my-channel, user_id =  }

How do I go about accessing just the data element and converting it into some usable values in my code? eg: Just turn the value of foo into a string var.

Any guidance here would be gratefully received.

benw-pusher commented 1 year ago

You can use the Unity JsonUtility to deserialize the JSON into an object that you can then get values from. To do so you need to define a type for the deserialized object. For example, if you are receiving chat messages you might have code similar to the below:

//define the ChatMessage class
public class ChatMessage
{
    public int userId;
    public string chatMessage;
}

//binding to the event and getting the chat message

        _channel.Bind("chat", (PusherEvent eventData) =>
        {       
            ChatMessage incomingMessage = JsonUtility.FromJson<ChatMessage>(eventData.Data);
            Debug.Log("new message: " + incomingMessage.chatMessage.ToString());
        });

With the event structure as

{
    "userId": req.params.character,
    "chatMessage": req.body.chatMessage
  }

Let us know if that helps.

benw-pusher commented 1 year ago

We haven't had a response here so it is likely you have moved on - if that is not the case please let us know via https://support.pusher.com/hc/en-us/requests/new and we can progress with you.