有人能给我看一个代码示例,展示如何将对象序列化为JSON吗?

时间:2013-05-28 01:30:10

标签: c# json azure

我有:

    MemoryStream stream1 = new MemoryStream();
    DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(UserTask));
    s.WriteObject(stream1, task);
    stream1.Position = 0;
    StreamReader sr = new StreamReader(stream1);
    Trace.Write("JSON form of Person object: ");
    Trace.WriteLine(sr.ReadToEnd());
    string json = sr.ReadToEnd();

    ASCIIEncoding encoding = new ASCIIEncoding();

    byte[] data = encoding.GetBytes(json);

    logger.Write("Attempting to post the foillowing JSON data: " + json);
    Trace.WriteLine("Attempting to post the foillowing JSON data: " + json);
    // Make a post to the other service
    HttpWebRequest httpWReq =
        (HttpWebRequest)WebRequest.Create(@"https://some.company.url");
        //(HttpWebRequest)WebRequest.Create(@"https://some.company.url");


    httpWReq.Method = "POST";
    httpWReq.ContentType = "application/x-www-form-urlencoded";
    httpWReq.ContentLength = data.Length;

    using (Stream stream = httpWReq.GetRequestStream())
    {
        stream.Write(data, 0, data.Length);
    }
    HttpWebResponse response = null;
    string responseString = null;
    try
    {
        // Do some work that may result in a transient fault.
        retryPolicy.ExecuteAction(
          () =>
          {
              // Call a method that uses Windows Azure storage and which may
              // throw a transient exception. 
              response = (HttpWebResponse)httpWReq.GetResponse();
              responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
          });
    }

这实际上并没有通过网络将JSON发送到其他服务...... 我正在使用DataContractJsonSerializer,因为数据包含字典。如果数据有用,我可以发布数据的样子,但我认为那部分是有用的吗?

3 个答案:

答案 0 :(得分:3)

我个人更喜欢使用Json.Net from James Newton-King

安装nuget包。 enter image description here

接下来,只需序列化它。

var users = GetUsersFromDatabase();
var json = JsonConvert.SerializeObject(users, Formatting.Indented);

如果您有一些json,并且希望将其转换为富对象,那么我们可以轻松地对其进行反序列化。

在这个例子中,让我们有一个包含用户的txt文件,采用有效的json格式......

var usersText = File.ReadAllText("C:\\Temp\\JsonUsers.txt");
var users = JsonConvert.DeserializeObject<IList<User>>(usersText);

答案 1 :(得分:2)

JavaScriptSerializer通常是一种很好的方法。

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

答案 2 :(得分:1)

JSON.NET是ASP.NET MVC用于JSON的默认库。您可以使用nuget获取它,然后使用静态类JsonConvert。

string json = JsonConvert.SerializeObject(task);