使用Web客户端的JSON序列化? [英] Using WebClient for JSON Serialization?

查看:155
本文介绍了使用Web客户端的JSON序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你可以反序列化的 JSON HttpWebResponse 使用 WebClient.DownloadString()但什么其他方式?我看了看MSDN页面,我不知道你是否能序列化到JSON对象或没有,谁知道?

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?

推荐答案

我觉得你可能只是有使用WebClient的实例之前序列化对象变成JSON。希望这有助于

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);

下面是从WebClient类发送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);
    }
}

下面是使用<$一个简单的辅助类C $ C> DataContractJsonSerializer 类序列化/反序列化对象和JSON。

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);
        }
    }
}

这篇关于使用Web客户端的JSON序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆