zoukankan      html  css  js  c++  java
  • C# JSON和对象之间互相转换

    1.首先是声明用户信息对象,DataContract修饰类,表示可以被解析成JSON,DataMember修饰属性,Order表示 解析的顺序,另外Lover是数组列表,表示女朋友个数

    Address 表示送货地址,DailyRecord  表示日常记录
    
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.Serialization;
    namespace FunctionTest.Model
    {
        [DataContract]
        public  class UserInfo
        {
            [DataMember(Order =0)]
            public string UserName { get; set; }
            [DataMember(Order = 1)]
            public int Age { get; set; }
            [DataMember(Order = 2)]
            public int Gender { get; set; }
            [DataMember(Order =3)]
            public List<string> Lover { get; set; }
            [DataMember(Order = 4)]
            public ContactAddress Address { get; set; }
            [DataMember(Order = 5)]
            public Dictionary<string, string> DailyRecord {
                get; set;
            }
        }
       
        [DataContract]
        public class ContactAddress
        {
            [DataMember(Order =0)]
            public string Province { get; set; }
            [DataMember(Order = 1)]
            public string City { get; set; }
            [DataMember(Order = 2)]
            public string Country { get; set; }
            [DataMember(Order = 3)]
            public string Details { get; set; }
        }
    }

    2.JSON帮助类 核心代码

          /// <summary>
          /// Json转换成对象
          /// </summary>
          /// <typeparam name="T"></typeparam>
          /// <param name="jsonText"></param>
          /// <returns></returns>
            public static T JsonToObject<T>(string jsonText)
            {
                DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(T));
                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
                T obj = (T)s.ReadObject(ms);
                ms.Dispose();
                return obj;
            }
            /// <summary>
            /// 对象转换成JSON
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="obj"></param>
            /// <returns></returns>
            public static string ObjectToJSON<T>(T obj)
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                string result = string.Empty;
                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, obj);
                    ms.Position = 0;
    
                    using (StreamReader read = new StreamReader(ms))
                    {
                        result = read.ReadToEnd();
                    }
                }
                return result;
            }

    3.调用 

                //1.对象-->JSON
                UserInfo info = new UserInfo
                {
                    Age = 10,
                    Gender = 1,
                    UserName = "刘德华",
                    Lover = new List<string> { "美女1", "美女2", "美女3" },
                    Address = new ContactAddress
                    {
                        Province = "湖南省",
                        City = "长沙市",
                        Country = "望城县",
                        Details = "某旮旯快递找不到的地方"
                    },
                    DailyRecord = new Dictionary<string, string> { { "星期一", "吃饭" }, { "星期二", "洗衣服" }, { "星期三", "好事情" } }
                };
            
                string json = ObjectToJSON<UserInfo>(info);

     4.反序列化后的结果

    {"UserName":"刘德华","Age":10,"Gender":1,"Lover":["美女1","美女2","美女3"],"Address":{"Province":"湖南省","City":"长沙市","Country":"望城县","Details":"某旮旯快递找不到的地方"},"DailyRecord":[{"Key":"星期一","Value":"吃饭"},{"Key":"星期二","Value":"洗衣服"},{"Key":"星期三","Value":"好事情"}]}
  • 相关阅读:
    移动零
    移除元素
    Ubuntu下安装PIL
    CSS颜色代码大全
    Test__GUI__用java编写一个简单的记事本程序,打包成jar双击运行
    Test__GUI__列出指定目录内容
    GUI__【GUI概述】【布局】【Frame】【事件监听机制】【窗体事件】【按钮】【鼠标事件】【键盘事件】【Dialog对话框】【菜单】
    Test__IO流综合应用的小练习
    IO流__【转换流的字符编码】【编码与解码】【字符编码-“联通”】
    IO流__【对象的序列化】【管道流】【RandomAccessFile】【DataStream】【ByteArrayStream等】
  • 原文地址:https://www.cnblogs.com/HCCZX/p/5238556.html
Copyright © 2011-2022 走看看