c#里string和Json转换

这里要用到如下两个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转换,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。