Json序列化的时候跳过加密字段

字段类定义如下
  public class Field
{
public bool IsEncrypted { get; set; } public string Name { get; set; } public Object Value { get; set; }
}

需要序列化User类

public class User
{
public Field UserName { get; set; } public Field Password { get; set; }
}

序列化的结果,加密字段密码也被序列化出来了

[Test]
public void TestChuck()
{
User user = new User();
Field field = new Field();
field.IsEncrypted = false;
field.Name = "UserName";
field.Value = "chucklu";
user.UserName = field; field = new Field();
field.IsEncrypted = true;
field.Name = "Password";
field.Value = "";
user.Password = field; string str = JsonConvert.SerializeObject(user);
Console.WriteLine(str);
}

{
"UserName": {
"IsEncrypted": false,
"Name": "UserName",
"Value": "chucklu"
},
"Password": {
"IsEncrypted": true,
"Name": "Password",
"Value": "123456"
}
}

https://stackoverflow.com/questions/18521970/custom-serializer-for-just-one-property-in-json-net

You can add a custom serializer to a single attribute like this:

public class Comment
{
public string Author { get; set; } [JsonConverter(typeof(NiceDateConverter))]
public DateTime Date { get; set; } public string Text { get; set; }
} public class NiceDateConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var date = value as DateTime;
var niceLookingDate = date.ToString("MMMM dd, yyyy 'at' H:mm tt");
writer.WriteValue(niceLookingDate);
} public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
} public override bool CanRead
{
get { return false; }
} public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime);
}
}

Then, when you serialize your object with JsonConvert.SerializeObject(), the custom serializer will be used for the Date property.

解决方案

继承JsonConverter实现自定义的Converter,FieldConverter,然后在属性上添加[JsonConverter(typeof(FieldConverter))]

 public class User
{
public Field UserName { get; set; } [JsonConverter(typeof(FieldConverter))]
public Field Password { get; set; }
} public class Field
{
public bool IsEncrypted { get; set; } public string Name { get; set; } public object Value { get; set; }
}
  public class FieldConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is Field field && !field.IsEncrypted)
{
var str = JsonConvert.SerializeObject(value);
writer.WriteValue(str);
}
} public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
} public override bool CanConvert(Type objectType)
{
return objectType == typeof(Field);
}
}

输出结果是

{
"UserName": {
"IsEncrypted": false,
"Name": "UserName",
"Value": "chucklu"
},
"Password": null
}

类似的,如果Field 这样使用List<Field>

 public class User
{
public List<Field> list = new List<Field>();
} public class Field
{
public bool IsEncrypted { get; set; } public string Name { get; set; } public object Value { get; set; }
}
  [Test]
public void TestChuck()
{
User user = new User();
Field field = new Field();
field.IsEncrypted = false;
field.Name = "UserName";
field.Value = "chucklu";
user.list.Add(field); field = new Field();
field.IsEncrypted = true;
field.Name = "Password";
field.Value = "";
user.list.Add(field); string str = JsonConvert.SerializeObject(user);
Console.WriteLine(str);
}

输出是

{
"list": [
{
"IsEncrypted": false,
"Name": "UserName",
"Value": "chucklu"
},
{
"IsEncrypted": true,
"Name": "Password",
"Value": "123456"
}
]
}

方案

唯一的问题是,把转义的双引号打出来了   使用 writer.WriteRawValue(str);可以避免json字符串被内部转义

  public class FieldConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is List<Field> list)
{
var temp = list.Where(x => !x.IsEncrypted).ToList();
var str = JsonConvert.SerializeObject(temp);
writer.WriteValue(str);
  writer.WriteRawValue(str);
}
} public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
} public override bool CanConvert(Type objectType)
{
return objectType == typeof(List<Field>);
}
}

{"list":"[{\"IsEncrypted\":false,\"Name\":\"UserName\",\"Value\":\"chucklu\"}]"}   本来[]两边是没有双引号的,里面的转义也是多出来的

{"List":[{"IsEncrypted":false,"Name":"UserName","Value":"chucklu"}]} 必须是 writer.WriteRawValue(str);

如果是 writer.WriteRaw(str);的话,结果中会多出一个null

custom serializer for just one property in Json.NET的更多相关文章

  1. js使用s:property标签接收json格式数据

    js使用s:property接收json数据时,会出现字符被转译的错误. 错误如下: 引号会被转译成'"'字符,导致解析不了. 错误原因: html的s:property接收不会出错,而js ...

  2. Extending JMeter – Creating Custom Config Element – Property File Reader

    JMeter is one of the best open source tools in the Test Automation Community. It comes with all the ...

  3. 【ASP.NET Web API教程】6.2 ASP.NET Web API中的JSON和XML序列化

    谨以此文感谢关注此系列文章的园友!前段时间本以为此系列文章已没多少人关注,而不打算继续下去了.因为文章贴出来之后,看的人似乎不多,也很少有人对这些文章发表评论,而且几乎无人给予“推荐”.但前几天有人询 ...

  4. Asp MVC 中处理JSON 日期类型

    注:时间有点忙,直接copy 过来的,要查看原址: http://www.developer.com/net/dealing-with-json-dates-in-asp.net-mvc.html I ...

  5. Json.NET Updates: Merge, Dependency Injection, F# and JSONPath Support

    Json.NET 6.0 received 4 releases this year, the latest last week. Over these releases, several new f ...

  6. Json序列化之.NET开源类库Newtonsoft.Json

    上代码: using System; using System.Collections; using System.Collections.Generic; using System.IO; usin ...

  7. JSON,全称:JavaScript Object Notation,作为一个常见的轻量级的数据交换格

    JSON,全称:JavaScript Object Notation,作为一个常见的轻量级的数据交换格式,应该在一个程序员的开发生涯中是常接触的.简洁和清晰的层次结构使得 JSON 成为理想的数据交换 ...

  8. WebApi接口 - 响应输出xml和json

    格式化数据这东西,主要看需要的运用场景,今天和大家分享的是webapi格式化数据,这里面的例子主要是输出json和xml的格式数据,测试用例很接近实际常用情况:希望大家喜欢,也希望各位多多扫码支持和点 ...

  9. .Net深入实战系列—JSON序列化那点事儿

    序 当前主流的序列化JSON字符串主要有两种方式:JavaScriptSerializer及Json.net(Nuget标识:Newtonsoft.Json).JavaScriptSerializer ...

随机推荐

  1. idea的类头注释和方法注释的编辑

    一:配置类头注释 1:点击file,点击settings 2:点击editor,选择 file and code template ,然后看右侧部分点击include,之后选中File Header ...

  2. [SDOI2016]征途 —— 斜率优化DP

    时隔多年没有碰斜率优化了... 想当年被斜率优化虐的死去活来,现在看看...也就那样吧. Pine开始了从S地到T地的征途. 从S地到T地的路可以划分成n段,相邻两段路的分界点设有休息站. Pine计 ...

  3. mooc-IDEA 使用界面--001

    IntelliJ IDEA 快捷键应用小结 1.Ctrl+E :  打开最近所有浏览过的文件 2.Ctrl+Shift+E :打开最近所有编辑修改过的文件 3.ctrl+shift+Backspace ...

  4. MVC Html.AntiForgeryToken(); 防止跨站伪造请求(建议所有表单提交都加这个)

    视图页面from表单中添加 @Html.AntiForgeryToken(); 然后每个表单提交的时候都会带__RequestVerificationToken 字段 后端控制器验证时添加  [Val ...

  5. java学习day3运算符

    一.算数运算符 1.对于除号“/”,它的整数除和小数除是有区别的:当整数除以整数的时候,会把结果的小数部分舍弃,只保留整数部分,例如: int x=3510; x=x/1000; 输出结果为x=3; ...

  6. NameVirtualHost的使用

    如果某个ip:port 上只设置了一个虚拟主机,那么NameVirtualHost ip:port 可以不写,因为从这个ip:port的访问不需要做任何选择:如上例中192.168.1.197只对应于 ...

  7. 如何在nuxt中添加proxyTable代理

    背景 在本地开发vue项目的时候,当你习惯了proxyTable解决本地跨域的问题,切换到nuxt的时候,你会发现,添加了proxyTable设置并没有什么作用,那是因为你是用的vue脚手架生成的vu ...

  8. Codeforces - 1199C - MP3 - 尺取

    https://codeforc.es/contest/1199/problem/C 擦,最后移位运算符溢出了,真的蠢. 肯定是选中间的连续的某段是最优的,维护这个段的长度和其中的元素种类就可以了.小 ...

  9. SpringBoot中设置自定义拦截器

    SpringBoot中设置自动以拦截器需要写一个类继承HandlerInterceptorAdapter并重写preHandle方法 例子 public class AuthorityIntercep ...

  10. web前端工程化

    目标 1.能够了解模块化的相关规范 2.了解webpack 3.了解使用Vue单文件组件 4.能够搭建Vue脚手架 5.掌握Element-UI的使用 1.模块化的分类 A.浏览器端的模块化 1).A ...