• C#/.net/WCF 使用DataMember Order 无视属性自上而下的输出顺序,自定义Json输出排序,该方法大神也不一定会!


     1  static void Main(string[] args)
     2         {
     3             Models m = new Models() { a = "1", b = "2" };
     4             string json=JsonSerializer<Models>(m);
     5             Console.WriteLine(json);
     6             //输出结果:b在a前边
     7             //{"b":"2","a":"1"}
     8         }
     9         //自定义类
    10         [DataContract]
    11         public class Models
    12         {
    13             //Order索引从0开始,越小越靠前
    14             [DataMember(Order = 2)]
    15             public string a { get; set; }
    16             [DataMember(Order = 1)]
    17             public string b { get; set; }
    18 
    19         }
    20         //JSON序列化
    21         public static string JsonSerializer<T>(T t)
    22         {
    23             DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
    24             MemoryStream ms = new MemoryStream();
    25             ser.WriteObject(ms, t);
    26             string jsonString = Encoding.UTF8.GetString(ms.ToArray());
    27             ms.Close();
    28             return jsonString;
    29         }
    30         /// <summary>
    31         /// JSON反序列化
    32         /// </summary>
    33         public static T JsonDeserialize<T>(string jsonString)
    34         {
    35             DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
    36             MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
    37             T obj = (T)ser.ReadObject(ms);
    38             return obj;
    39         }
  • 相关阅读:
    CentOS7源码安装 mplayer-1.1
    CentOS6开关机日志查询
    Redis GUI客户端
    CST & UTC时间差
    FreeBSD10.0 PXE安装
    PostgreSQL9.6源码安装
    phpPgAdmin-5.1安装配置
    js截取文件名不带后缀
    在MongoDB中修改数据类型
    win10怎么修改DNS
  • 原文地址:https://www.cnblogs.com/ylblogss/p/10689829.html
Copyright © 2020-2023  润新知