很多情况下,我们需要把数据类型做一些转换,供其它外部的子系统调用。

最为典型的是生成json格式供javascript作调用。

现成的组件Newtonsoft.Json可以实现object2json之间的转换。

Newtonsoft.Json.JavaScriptConvert.SerializeObject(object)可以执行json的序列化,也是反序列化的方法。

常见的场景:

A系统提供用户资料(MemberInfo)给子系统B调用,但用户资料中有些内容是不能公开的,如Email地址。

本文由网页教学网(www.webjx.com)发布!转载和采集的话请不要去掉!谢谢。

直接用Newtonsoft.Json.JavaScriptConvert.SerializeObject好像是不行的,它会把object中的所有属性列出。

我的做法是这样的:

定义一个特性类,该特性类只允许用于类的属性上

view plaincopy to clipboardprint?
[AttributeUsage(AttributeTargets.Property)]   
    public class DenyReflectionAttrubite : Attribute   
    {   
        public DenyReflectionAttrubite() { }   
    }

[AttributeUsage(AttributeTargets.Property)]
    public class DenyReflectionAttrubite : Attribute
    {
        public DenyReflectionAttrubite() { }
    }

MemberInfo类
view plaincopy to clipboardprint?
public class MemberInfo   
    {   
        public int Uid   
        {   
            get;   
            set;   
        }   
        public string UserName   
        {   
            get;   
            set;   
        }   
           
        public string NickName   
        {   
            get;   
            set;   
        }   
        [DenyReflectionAttrubite]   
        public string Password   
        {   
            get;   
            set;   
        }   
       [DenyReflectionAttrubite]   
        public string Email   
        {   
            get;   
            set;   
        }   
//.......................   
}

public class MemberInfo
    {
        public int Uid
        {
            get;
            set;
        }
        public string UserName
        {
            get;
            set;
        }
        
        public string NickName
        {
            get;
            set;
        }
        [DenyReflectionAttrubite]
        public string Password
        {
            get;
            set;
        }
       [DenyReflectionAttrubite]
        public string Email
        {
            get;
            set;
        }
//.......................
}

至于DenyReflectionAttrubite特性如何使用,下面就会提出。
json生成
view plaincopy to clipboardprint?
public void Builder()   
        {   
            using (jsonWriter = new JsonTextWriter(sw))   
            {   
                   
                jsonWriter.Formatting = Formatting.None;   
                jsonWriter.Indentation = 4;   
                jsonWriter.WriteStartObject();   
                   
                jsonWriter.WritePropertyName("member");   
                jsonWriter.WriteStartArray();   
                jsonWriter.WriteStartObject();   
                Type settingsType = this.member.GetType();   
                foreach (PropertyInfo propertyInformation in settingsType.GetProperties())   
                {   
                    try  
                    {   
                        //在这里对DenyReflectionAttrubite特性的属性跳过处理   
                        if (propertyInformation.GetCustomAttributes(typeof(DenyReflectionAttrubite), false).Length > 0) continue;      
                        object propertyValue = propertyInformation.GetValue(member, null);   
                        string valueAsString = propertyValue.ToString();   
                        if (propertyValue.Equals(null))   
                        {   
                            valueAsString = String.Empty;   
                        }   
                        if (propertyValue.Equals(Int32.MinValue))   
                        {   
                            valueAsString = String.Empty;   
                        }   
                        if (propertyValue.Equals(Single.MinValue))   
                        {   
                            valueAsString = String.Empty;   
                        }   
                        jsonWriter.WritePropertyName(propertyInformation.Name.ToLower());   
                        jsonWriter.WriteValue(valueAsString.Trim());   
                    }   
                    catch { }   
  
                }   
  
                jsonWriter.WriteEndObject();   
                jsonWriter.WriteEnd();   
                jsonWriter.WriteEndObject();   
            }   
        }

public void Builder()
        {
            using (jsonWriter = new JsonTextWriter(sw))
            {
                
                jsonWriter.Formatting = Formatting.None;
                jsonWriter.Indentation = 4;
                jsonWriter.WriteStartObject();
                
                jsonWriter.WritePropertyName("member");
                jsonWriter.WriteStartArray();
                jsonWriter.WriteStartObject();
                Type settingsType = this.member.GetType();
                foreach (PropertyInfo propertyInformation in settingsType.GetProperties())
                {
                    try
                    {
                        //在这里对DenyReflectionAttrubite特性的属性跳过处理
                        if (propertyInformation.GetCustomAttributes(typeof(DenyReflectionAttrubite), false).Length > 0) continue;   
                        object propertyValue = propertyInformation.GetValue(member, null);
                        string valueAsString = propertyValue.ToString();
                        if (propertyValue.Equals(null))
                        {
                            valueAsString = String.Empty;
                        }
                        if (propertyValue.Equals(Int32.MinValue))
                        {
                            valueAsString = String.Empty;
                        }
                        if (propertyValue.Equals(Single.MinValue))
                        {
                            valueAsString = String.Empty;
                        }
                        jsonWriter.WritePropertyName(propertyInformation.Name.ToLower());
                        jsonWriter.WriteValue(valueAsString.Trim());
                    }
                    catch { }

}

jsonWriter.WriteEndObject();
                jsonWriter.WriteEnd();
                jsonWriter.WriteEndObject();
            }
        }

转载自:http://www.aspnetjia.com

组件Newtonsoft.Json实现object2json转换的更多相关文章

  1. Newtonsoft.Json 把对象转换成json字符串

    var resultJson = new { records = rowCount, page = pageindex, //总页数=(总页数+页大小-1)/页大小 total = (rowCount ...

  2. C#将集合和Json格式互相转换的几种方式

    1.使用微软自带的System.Web.Extensions.dll转换,该DLL文件一般存在于如下路径:c:\Program Files\Reference Assemblies\Microsoft ...

  3. Newtonsoft.Json日期转换

    在使用EasyUI做后台时,使用表格datagrid,用Newtonsoft.Json转换为Json格式后,时间显示为2013-06-15 T00:00:00形式. 后来研究了一下Newtonsoft ...

  4. Newtonsoft.Json转换强类型DataTable错误:Self referencing loop detected with type ......

    问题,在使用Newtonsoft.Json对强类型的DataTable进行系列化时会出现循环引用错误 解决办法,不要直接系列化强类型的DataTable,改为 JsonConvert.Serializ ...

  5. Newtonsoft.Json 转换DateTime类型为字符串时,串内部会有一个T。解决方案

    使用Newtonsoft.Json 转换DateTime类型时,若使用标准转换,则字符串内会有一个T(虽然再转换成DateTime没有问题). 若要转换成DateTime没有T,可以加上特性: pub ...

  6. Asp.Net中使用Newtonsoft.Json转换,读取,写入

    using Newtonsoft.Json;using Newtonsoft.Json.Converters; //把Json字符串反序列化为对象目标对象 = JsonConvert.Deserial ...

  7. Net Core 下 Newtonsoft.Json 转换字符串 null 替换成string.Empty

    原文:Net Core 下 Newtonsoft.Json 转换字符串 null 替换成string.Empty public class NullToEmptyStringResolver : De ...

  8. 【转载】 C#使用Newtonsoft.Json组件来反序列化字符串为对象

    在Asp.Net网站开发的过程中,很多时候会遇到对象的序列化和反序列化操作,Newtonsoft.Json组件是专门用来序列化和反序列化操作的一个功能组件,引入这个DLL组件后,就可使用JsonCon ...

  9. 【转载】C#使用Newtonsoft.Json组件来序列化对象

    在Asp.Net网站开发的过程中,很多时候会遇到对象的序列化和反序列化操作,Newtonsoft.Json组件是专门用来序列化和反序列化操作的一个功能组件,引入这个DLL组件后,就可使用JsonCon ...

随机推荐

  1. springmvc下js控制表单提交(表单提交前检验,提交后获取json返回值)

    这个问题我搞了四天,终于搞懂.因为对js很不熟悉.郁闷的是后台代码出错总可以设置断点调试,前端js代码出错只能通过浏览器提供一些运行数据来分析,很不习惯. 首先说下逻辑:这是一个注册功能,我希望,注册 ...

  2. CocoaPods 深入使用

    在 CocoaPods 使用中介绍了基本的使用 写项目的时候想用到 SQLite.swift第三方库,但是问题来了 pod search SQLite.swift  //执行这条语句,搜索不到结果 但 ...

  3. redis启动流程介绍

    转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/114.html?1455860562 1. 准备运行环境 * 设置oom ...

  4. Atiit 如何手写词法解析器

    Atiit 如何手写词法解析器 1.1. 通过编程直接从正则->nfa->dfa->表驱动词法解析一条龙自动生成.那是用程序自动生成是需要这样的,自己手写完全不必要这么复杂1 1.2 ...

  5. Atitit 为什么网络会有延时 电路交换与分组交换的区别

    Atitit 为什么网络会有延时 电路交换与分组交换的区别 按道理,网络是电子设备联网,应该达到光速才对.. 本质上因为互联网基于分组交换而不是电路交换. 分组交换相当于队列方式,别人发你的数据包先存 ...

  6. rabbitmq消息队列——"路由"

    在之前的教程中,我们创建了一个简单的日志系统.我们能够向许多交换器转发日志消息. 在本教程中,我们将添加一个功能--我们让它仅仅接收我们感兴趣的日志类别.举例:我们 实现仅将严重级别的错误日志写入磁盘 ...

  7. angularjs的resource实例对象

    angularjs的resource实例对象 我们看看都有啥 而直接使用service对象的时候没有前面这些$

  8. KnockoutJS 3.X API 第五章 高级应用(2) 控制后代绑定

    注意:这是一种高级技术,通常仅在创建可重用绑定的库时使用. 默认情况下,绑定仅影响它们应用到的元素. 但是如果你想影响所有的后代元素呢? 为此,只需从绑定的init函数中返回{controlsDesc ...

  9. 快速入门系列--MVC--02路由

    现在补上URL路由的学习,至于蒋老师自建的MVC小引擎和相关案例就放在论文提交后再实践咯.通过ASP.NET的路由系统,可以完成请求URL与物理文件的分离,其优点是:灵活性.可读性.SEO优化.接下来 ...

  10. CSS默认可继承样式

    前面的话 一直想总结出一份可继承样式的列表.常听说,颜色和字体是可继承的,盒模型样式是不可继承的,但其他样式呢?本文内容包括所有可继承的样式 [注意]关于样式的详细信息移步至此 常用可继承样式 col ...