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. Temporal-Difference Learning for Prediction

    In Monte Carlo Learning, we've got the estimation of value function: Gt is the episode return from t ...

  2. 应用安全 - 代码审计 -Java

    Java %c0%ae 安全模式绕过漏洞 原理 在Java端"%c0%ae"解析为"\uC0AE",最后转义为ASCCII低字符-".".通 ...

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

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

  4. WPF资源字典的使用

    1.在解决方案中添加资源字典:鼠标右键——添加——资源字典 2.在资源字典中写入你需要的样式,我这里简单的写了一个窗体的边框样式 3.在App.xaml中加入刚刚新建的资源字典就好了

  5. 《剑指offer》面试题16 反转链表 Java版

    (输入链表的头节点,反转链表) 书中方法:对于一个链表,我们只能从头往后遍历,如果要反转,我们需要更改当前节点的next域指向前一个节点,此时链表断开,为了能继续修改下一个节点的next域,我们还要维 ...

  6. linux驱动模型——platform(1)

    一.驱动模型包含什么? 1.1. 类class 1.1.2. 它能够自动创建/dev下的设备节点,不需要mknod /dev/xxx c x x创建.当然class还有其另外的作用,且自动创建设备节点 ...

  7. java 多态 (知识点不完整)

    1.多态的条件 1.要有继承 2.方法重写 3.父类引用指向子类对象 多态中成员访问 1.   访问成员变量:  编译看左边,运行也看左边 f.num = 10 因为这里是父类的,看是父类Father ...

  8. SQL结构化查询语言

    一.SQL 结构化查询语言 1.T-SQL 和 SQL的关系 T-SQL是SQL的增强版 2.SQL的组成 2.1 DML (数据操作语言) 增加,修改,删除等数据操作 2.2 DCL (数据控制语言 ...

  9. JavaScript基础5——动态显示时间

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  10. 微信小程序倒计时实现功能

    onLoad: function () {    var that=this;    this.data.intervarID= setInterval(function () {      var ...