1

I'm trying to pass an object over a StreamSocket, so i need to serialize it before i can do that.

I looked at the BinaryFormatter, but that doesn't seem to be available in UWP? Any suggestions on how to serialize an object, and preferably in the most compact way.

Christian Bekker
  • 1,857
  • 4
  • 27
  • 43

2 Answers2

3

You can serialize your own .NET objects; JSON.NET is a very popular choice, but the built-in DataContractSerializer should also work if you don't want any dependencies.

You cannot serialize any WinRT objects.

Peter Torr - MSFT
  • 11,824
  • 3
  • 18
  • 51
0

If you want to serialize an object to json, at first you have to add Newtonsoft.Json to your project.

To install Json.NET, run the following command in the Package Manager Console:

PM> Install-Package Newtonsoft.Json

Then use this code to pass your object :

(Note: In this sample I suppose your server and client are the same and the port that you are using is: 1800.)

        try
        {
            Windows.Networking.Sockets.StreamSocket socket = new Windows.Networking.Sockets.StreamSocket();
            Windows.Networking.HostName serverHost = new Windows.Networking.HostName("127.0.0.1");
            string serverPort = "1800";
            socket.ConnectAsync(serverHost, serverPort);
            var json = JsonConvert.SerializeObject(object);
            byte[] buffer = Encoding.UTF8.GetBytes(json);
            Stream streamOut = socket.OutputStream.AsStreamForWrite();
            StreamWriter writer = new StreamWriter(streamOut);
            var request = json;
            writer.WriteLine(request);
            writer.Flush();

            Stream streamIn = socket.InputStream.AsStreamForRead();
            StreamReader reader = new StreamReader(streamIn);
            string response = reader.ReadLine();
        }
        catch (Exception e)
        {
            var err = e.Message;
            //Handle exception here.            
        }

Inform me if you have any other question.

Hamed
  • 590
  • 5
  • 16