将获取到的json字符串序列化转为实体类

最近在优化内存。

由于url参数过多,满篇幅都是context.Request,为了精简,采用前端传递一个参数后面跟json对象,后台获取序列化的方式处理。

网上找到大篇幅的都是在wcf中调用。很多类库不全,所以使用了如下方式进行调用


前端代码:

function urlObj(SlideID,Zoom,FileNum,level,PositionX,PositionY,TileSize,r,g,b,bright,contrast,gamma,saturation,hues,kis) {
			var a={
				SlideID:SlideID,
				Zoom:Zoom,
				FileNum:FileNum,
				level:level,
				PositionX:PositionX,
				PositionY:PositionY,
				TileSize:TileSize,
				r:r,
				g:g,
				b:b,
				bright:bright,
				contrast:contrast,
				gamma:gamma,
				saturation:saturation,
				hues:hues,
				kis:kis,
			}
			return a;
		};

后端代码,实体类:

 [DataContract]
    public class UrlParam : IExtensibleDataObject
    {
      
        public UrlParam()
        { }
        [DataMember(Name = "SlideID")]
        public string SlideID { get; set; }

        [DataMember(Name = "Zoom")]
        public float Zoom { get; set; }

        [DataMember(Name = "FileNum")]
        public int FileNum { get; set; }

        [DataMember(Name = "level")]
        public int level { get; set; }

        [DataMember(Name = "PositionX")]
        public int PositionX { get; set; }

        [DataMember(Name = "PositionY")]
        public int PositionY { get; set; }

        [DataMember(Name = "TileSize")]
        public int TileSize { get; set; }

        [DataMember(Name = "r")]
        public int r { get; set; }

        [DataMember(Name = "g")]
        public int g { get; set; }

        [DataMember(Name = "b")]
        public int b { get; set; }

        [DataMember(Name = "bright")]
        public double bright { get; set; }

        [DataMember(Name = "contrast")]
        public int contrast { get; set; }

        [DataMember(Name = "gamma")]
        public float gamma { get; set; }

        [DataMember(Name = "saturation")]
        public double saturation { get; set; }

        [DataMember(Name = "hues")]
        public int hues { get; set; }

        [DataMember(Name = "kis")]
        public float kis { get; set; }

        private ExtensionDataObject extensionDatavalue;
        public ExtensionDataObject ExtensionData
        {
            get
            {
                return extensionDatavalue;
            }
            set
            {
                extensionDatavalue = value;
            }
        }
    }


后端代码,序列化:

   public static T Deserialize(string json)
        {
            T obj = Activator.CreateInstance();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                return (T)serializer.ReadObject(ms);
            }
        }

后台调用:

string json = context.Request["Param"];
UrlParam urlparam=Deserialize(json);


需要注意的是实体类要引用的类库:

System.Runtime.Serialization

System.Data.DataSetExtensions


调用时项目也需要调用类库:

System.Runtime.Serialization

你可能感兴趣的:(c#,工作中遇到的问题)