Json 动态设置需要转换的属性

寇剑 发布于 2012/06/12 11:42
阅读 1K+
收藏 0

问题是这样的,我有一个类,要转换为json,这个没有什么问题!这个类属性比较多,开有手机服务,考虑流量问题,手机每次访问只需要返回几个属性而已,如果将所有属性都转换为Json字符串返回,这个效果不太好!所以问一下我该怎样做呢,

以下是我的将对象转换为Json字符串的操作

 /// <summary>
        /// 将Object转化为二进制字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToString(object value)
        {
            DataContractJsonSerializer serizlizer = new DataContractJsonSerializer(value.GetType());
            MemoryStream stream = new MemoryStream();
            serizlizer.WriteObject(stream, value);

            return Encoding.UTF8.GetString(stream.ToArray());
        }
      
        /// <summary>
        /// 将一个列表对象序列化为字符串
        /// </summary>
        /// <param name="objs"></param>
        /// <returns></returns>
        public static string ObjectsToString(object values)
        {
            StringBuilder json = new StringBuilder();

            //json.Append("{\"lists\":");
            json.Append(ObjectToString(values));
            //json.Append("}");

            return json.ToString();
        }

        /// <summary>
        /// 将字符串反序列化为对象
        /// </summary>
        /// <param name="json">输入JSON字符串</param>
        /// <param name="objectType">序列化为对象的类型</param>
        /// <returns></returns>
        public static Object StringToObject(string json, Type objectType)
        {
            //string s = split("}");
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectType);
            MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(json));
            return serializer.ReadObject(mStream);
        }

加载中
0
郭大侠
郭大侠
IsRequired = true在编译时就已经静态确定了,不能算是动态。
0
寇剑
寇剑

谢谢各位了,这个问题我解决了!我是这样解决的!

 设置这些属性后,如果某一个属性没有赋值EmitDefaultValue = false,那么这个属性就在json转换中,不进行序列化,但是如果有一些属性虽然为null但是也必须进行序列化的,就要设置 IsRequired = true,谢谢各位浏览的朋友!

 [DataContract]
    public class Temp
    {
        private int id;
        private string name;

        [DataMemberAttribute(EmitDefaultValue = true, IsRequired = true, Name = "name")]
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private string address;
        [DataMemberAttribute(EmitDefaultValue = false, IsRequired = false, Name = "add")]
        public string Address
        {
            get { return address; }
            set { address = value; }
        }

        [DataMemberAttribute(EmitDefaultValue = false, IsRequired = false, Name = "hop")]
        private string hop;
        public string Hop
        {
            get { return hop; }
            set { hop = value; }
        }
        [DataMemberAttribute(EmitDefaultValue = false, IsRequired = true, Name = "id")]
        public int Id
        {
            get { return id; }
            set { id = value; }
        }
    }

返回顶部
顶部