custom serializer for just one property in Json.NET
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的更多相关文章
- js使用s:property标签接收json格式数据
js使用s:property接收json数据时,会出现字符被转译的错误. 错误如下: 引号会被转译成'"'字符,导致解析不了. 错误原因: html的s:property接收不会出错,而js ...
- 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 ...
- 【ASP.NET Web API教程】6.2 ASP.NET Web API中的JSON和XML序列化
谨以此文感谢关注此系列文章的园友!前段时间本以为此系列文章已没多少人关注,而不打算继续下去了.因为文章贴出来之后,看的人似乎不多,也很少有人对这些文章发表评论,而且几乎无人给予“推荐”.但前几天有人询 ...
- Asp MVC 中处理JSON 日期类型
注:时间有点忙,直接copy 过来的,要查看原址: http://www.developer.com/net/dealing-with-json-dates-in-asp.net-mvc.html I ...
- 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 ...
- Json序列化之.NET开源类库Newtonsoft.Json
上代码: using System; using System.Collections; using System.Collections.Generic; using System.IO; usin ...
- JSON,全称:JavaScript Object Notation,作为一个常见的轻量级的数据交换格
JSON,全称:JavaScript Object Notation,作为一个常见的轻量级的数据交换格式,应该在一个程序员的开发生涯中是常接触的.简洁和清晰的层次结构使得 JSON 成为理想的数据交换 ...
- WebApi接口 - 响应输出xml和json
格式化数据这东西,主要看需要的运用场景,今天和大家分享的是webapi格式化数据,这里面的例子主要是输出json和xml的格式数据,测试用例很接近实际常用情况:希望大家喜欢,也希望各位多多扫码支持和点 ...
- .Net深入实战系列—JSON序列化那点事儿
序 当前主流的序列化JSON字符串主要有两种方式:JavaScriptSerializer及Json.net(Nuget标识:Newtonsoft.Json).JavaScriptSerializer ...
随机推荐
- FormData模拟表单上传图片
[node]---multer模块实现图片上传---FORMDATA 1.安装muterl第三方模块 cnpm install multer --save 2.使用 multer在解析完成后,会向 ...
- Haystack Python全文检索框架
Haystack 1.什么是Haystack Haystack是django的开源全文搜索框架(全文检索不同于特定字段的模糊查询,使用全文检索的效率更高 ),该框架支持Solr,Elasticsear ...
- 21次C++作业
//第一题目 class A //A为基类 {public: void f1( ); int i; protected: void f2(); int j; private: int k; }; /* ...
- 两道CTF Web的题目
1.easyphp 1.1.题目描述 题目首先是一张不存在的图片 查看源码发现只有一句话 <img src="show.php?img=aGludC5qcGc=" width ...
- 基于Filter实现Gzip数据压缩
在web开发中,当服务器端向客户端返回的数据量比较大时,我们可以通过Gzip对数据进行压缩处理 注意:如果小数据量进行压缩,压缩后的数据可能比原始数据还大:所以response返回数据量比较小时不推荐 ...
- Spring Boot 集成 Ehcache 缓存,三步搞定!
作者:谭朝红 www.ramostear.com/articles/spring_boot_ehcache.html 本次内容主要介绍基于Ehcache 3.0来快速实现Spring Boot应用程序 ...
- 模块管理常规功能自己定义系统的设计与实现(15--进一步完好"省份"模块)
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/jfok/article/details/24737483 "省份"模块的进一步完 ...
- SQL在Oracle内部的具体处理流程
下图显示了SQL在Oracle内部处理的一般阶段:解析.优化.产生行源和执行.数据库可能会忽略某些步骤,这取决于具体的语句. ...
- Log4Net 之走进Log4Net (四)
原文:Log4Net 之走进Log4Net (四) 一.Log4net的结构 log4net 有四种主要的组件,分别是Logger(记录器), Repository(库), Appender(附着器) ...
- jenkins使用记录转自https://my.oschina.net/sanpeterguo/blog/197931
摘要: jenkins(持续集成开源工具)提供了丰富的api接口,基本上所有的操作都可以使用curl来从后台调度,包括:创建项目,禁用项目,启用项目,获取项目描述,获取配置文件,普通触发,scm触发, ...