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. 浅谈Java反射机制 之 获取类的字节码文件 Class.forName("全路径名") 、getClass()、class

    另一个篇:获取 类 的 方法 和 属性(包括构造函数) 先贴上Java反射机制的概念: AVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法: 对于任意一个对象,都能够调用它 ...

  2. Websocket如何建立连接

    前面提到,WebSocket复用了HTTP的握手通道.具体指的是,客户端通过HTTP请求与WebSocket服务端协商升级协议.协议升级完成后,后续的数据交换则遵照WebSocket的协议. 1.客户 ...

  3. glibc升级,解决glib版本过低的问题

    Debian wheezy下的glibc版本为2.13,安装几个软件都运行不了,报以下类似错误:xxxx: /lib/i386-linux-gnu/i686/cmov/libc.so.6: versi ...

  4. vue --》watch 深度监听的优化。

    话不多说,直接上代码,注释很清楚 <template> <div> <input type="text" v-model="value&qu ...

  5. Mac入门--通过homebrew下载过慢问题

    使用国内的镜像替换homebrew镜像,对镜像进行加速源 原先我们执行brew命令安装的时候,跟3个仓库地址有关 1 brew.git 2 homebrew-core.git 3 homebrew-b ...

  6. 教你使用Python制作酷炫二维码

    这篇文章讲的是如何利用python制作狂拽酷炫吊炸天的二维码,非常有趣哦! 可能你见过的二维码大多长这样: 普普通通,平平凡凡,没什么特色... 但,如果二维码长这样呢! 或者 这样! 是不是炒鸡好看 ...

  7. jquery获取年月日时分秒当前时间

    获取年月日时分秒的当前时间,可按照某种格式显示出来,下面是一种得到如2017年02月02日  00:00:00格式的当前时间 function getCurrentDate(date){ var y ...

  8. 13、前端知识点--ajax原理以及实现过程

    一.简略版的 Ajax简介 Ajax(Asyncchronous JavaScript and Xml),翻译过来就是说:异步的javaScript和xml, Ajax不是新的编程语言,而是一种使用现 ...

  9. javascript实现快速排序算法

    忘记了快速排序的思路是怎样的了,复习一下,写了两个实例,发表博文备忘. 对于快速排序的思想,可以参考白话经典算法系列之六 快速排序 快速搞定,讲得比较通俗 prototype扩展的方式 /** * 对 ...

  10. asp.net webapi自定义输出结果类似Response.Write()

    asp.net webapi自定义输出结果类似Response.Write()   [HttpGet] public HttpResponseMessage HelloWorld() { string ...