12

I know you can deserialize a JSON object from an HttpWebResponse using the WebClient.DownloadString() but what about the other way around? I've looked at the MSDN pages and I don't know if you can serialize to JSON objects or not, anyone know?

2
  • Can you provide some sample pseudo code showing what you are trying to do with the WebClient class? Commented Aug 2, 2010 at 21:37
  • Serialize JSON so that I can send it via an HttpRequest for consumption of lets say an .ascx or even outside .NET. Just want to know if it's possible that's all. I don't see a way. Commented Aug 2, 2010 at 21:39

2 Answers 2

30

I think you may just have to serialize the object into JSON before using the WebClient instance. Hope this helps

var url = "...";
var json = JsonHelper.ToJson(myObject);

var response = PostJson(url, json);

Here's an example of sending JSON data from the WebClient class:

public static string PostJson(string url, string data)
{
    var bytes = Encoding.Default.GetBytes(data);

    using (var client = new WebClient())
    {
        client.Headers.Add("Content-Type", "application/json");
        var response = client.UploadData(url, "POST", bytes);

        return Encoding.Default.GetString(response);
    }
}

Here is a simple helper class that uses the DataContractJsonSerializer class to serialize / deserialize object to and from JSON.

public static class JsonHelper
{
    public static string ToJson<T>(T instance)
    {
        var serializer = new DataContractJsonSerializer(typeof(T));
        using (var tempStream = new MemoryStream())
        {
            serializer.WriteObject(tempStream, instance);
            return Encoding.Default.GetString(tempStream.ToArray());
        }
    }

    public static T FromJson<T>(string json)
    {
        var serializer = new DataContractJsonSerializer(typeof(T));
        using (var tempStream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
        {
            return (T)serializer.ReadObject(tempStream);
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, but I'm asking about the WebClient object here. I was trying to figure out if it's possible but do not see anything out there talking about that object being able to serialize...only deserialize.
3

I use :

var json = new JavaScriptSerializer().Serialize(yourObject);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.