首页 > 代码库 > c#里string和Json转换
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);}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。