Serializing objects to JSON in Windows 8 using C#

So In one of my old posts I was talking about how to deserialize JSON you can head there if you’re interested in that. Today I’m going to talk about how to serialize JSON and how to use HttpClient to post it to a service.

Converting object to JSON

For the first part you need to convert your C# object to a JSON string for doing that w have to ways, the first one is the native .NET framework way by making use of the DataContractJsonSerializer class under System.Runtime.Serialization.Json namespace and the second way is by making use of the JSON.NET library.

Serializing the objects to JSON(The Native way)

 MemoryStream stream = new MemoryStream();
 DataContractJsonSerializer jsonSer = 
 new DataContractJsonSerializer(typeof(Photo));
 jsonSer.WriteObject(stream, _photoObject);
 stream.Position = 0;
 StreamReader sr = new StreamReader(stream);
 var json = sr.ReadToEnd();
 So by using the above 6 lines of code you will be able to convert you object to a JSON string.

Serializing the objects to JSON(The Easy way)

My favorite library for JSON manipulations is JSON.NET. This library allows you to serialize and deserialize with a single line of code, directly to the objects you defined. You can use json2csharp to create your model, if you don’t have it available yet or you can use the newly visual studio introduced feature which will enable you to paste JSON as Classes, but in order to get that you have to install this update.

 var json = JsonConvert.SerializeObject(_photoObject);

Posting the JSON string

The last step now will be posting the JSON string to your web api or web service. We can easily do that using the HttpClient postAsync method. all what I will be doing is the following I am passing the URI and the post content which is in our case a JSON string then inside the content I am specifying the media type which is JSON. For more information about media types MIME.

 await client.PostAsync("api/photos",
 new StringContent(json, System.Text.Encoding.UTF8 , "application/json"));