首页 > Web开发 > 详细

c#里string和Json转换

时间:2014-07-23 11:49:46      阅读:487      评论:0      收藏:0      [点我收藏+]

这里要用到如下两个namespace:

using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;

定义Json实体类如下:

[DataContract]
public class TextMessage
{
    [DataMember(Name = "content")]
    public string Content { get; set; }
}

[DataContract]
public class CustomerMessage
{
    [DataMember(Name = "touser")]
    public string touser { get; set; }

    [DataMember(Name = "msgtype")]
    public string msgtype { get; set; }

    [DataMember(Name = "text")]
    public TextMessage textMsg { get; set; }
}

对象序列化为Json格式如下:

CustomerMessage message = new CustomerMessage()
{
    touser = OpenIDBox.Text,
    msgtype = "text",
    textMsg = new TextMessage()
    {
        Content = ContentBox.Text
    }
};

DataContractJsonSerializer json = new DataContractJsonSerializer(message.GetType());
string szJson = "";

//序列化
using (MemoryStream stream = new MemoryStream())
{
    json.WriteObject(stream, message);
    szJson = Encoding.UTF8.GetString(stream.ToArray());
}

Console.WriteLine(szJson);

 Json格式反序列化为对象如下:

retStr = "<Json String>";
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(retStr)))
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(CustomerMessage));
    CustomerMessage_message = (CustomerMessage)serializer.ReadObject(ms);
}

c#里string和Json转换,布布扣,bubuko.com

c#里string和Json转换

原文:http://www.cnblogs.com/chunyih/p/3861869.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!