C#——JSON操作类简单封装(DataContractJsonSerializer)

Framework版本:.Net Framework 4

使用DataContractJsonSerializer时,实体请使用注解,格式如下

1、实体使用注解,并且提供get和set的public访问器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization;
namespace ReligionServer.vo
{
    [DataContract]
    public class Inspection : Model.Inspection, IComparable<vo.Inspection>
    {

        [DataMember(Order = 0)]//Order表示输出顺序
        public new string Time { get; set; }

        [IgnoreDataMember]//表示不参与Json转换
        public String Msg { get; set; }

        public int Order { get; set; }

        [DataMember]
        public String Period { get; set; }

        int IComparable<Inspection>.CompareTo(Inspection other)
        {
            int result;
            //正序
            if (this.RTime > other.RTime) {
                result = 1;
            } else if (this.RTime < other.RTime) {
                result = -1;
            }
            else {
                result = 0;
            }
            //反序
            if (this.Order == -1)
            {
                if (result < 0) {
                    result = System.Math.Abs(result);
                } else if (result > 0) {
                    result = 0 - result;
                }
            }
            
            //我好蠢,这里做了排序,又对Service中对noCheckList做了分页(正序和反序分页)
            
            return result;
        }
    }
}

2、JSON工具源码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ReligionServer.util;
using System.Text;
using System.Runtime.Serialization.Json;

namespace ReligionServer.util {
    public class JsonUtil <T>{

        private static DataContractJsonSerializer jsonSerializer;
        private static T t;

        static JsonUtil(){
            t = (T)ReflectionUtil.Instance(new JsonUtil<T>().GetType());
            Console.WriteLine(t.GetType());
            jsonSerializer = new DataContractJsonSerializer(typeof(T));
        }

        public static String ObjToJson(T t){
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
                //System.Diagnostics.Debug.WriteLine(t);
                jsonSerializer.WriteObject(ms, t);
                //System.Diagnostics.Debug.WriteLine(ms.ToArray().Length);
                StringBuilder builder = new StringBuilder();
                builder.Append(Encoding.UTF8.GetString(ms.ToArray()));
                //System.Diagnostics.Debug.WriteLine(builder.Length);
                //System.Diagnostics.Debug.WriteLine(builder.ToString());
                return builder.ToString();
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/threadj/p/10536385.html