Christian Bekker
Christian Bekker

Reputation: 1867

Serialize object in UWP app

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.

Upvotes: 1

Views: 8364

Answers (2)

Hamed
Hamed

Reputation: 588

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.

Upvotes: 0

Peter Torr
Peter Torr

Reputation: 12019

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.

Upvotes: 3

Related Questions