zoukankan      html  css  js  c++  java
  • 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);
    }
    
  • 相关阅读:
    [SAP HANA] HANA 安装更新工具HDBLCM
    [SAP BASIS] [TMS] TMS相关的程序和后台作业
    [sap basis] [authorization trace] Disable/enable authorization trace
    IEEE 802.11 标准列表
    802.11 wireless 七
    802.11 wireless 六
    802.11 wireless 五
    802.11 wireless 四
    802.11 wireless 三
    802.11 wireless 二
  • 原文地址:https://www.cnblogs.com/chunyih/p/3861869.html
Copyright © 2011-2022 走看看