本文将介绍如何在反序列化之前使用System.Text.Json验证JSON的详细情况,特别是关于反序列化json数据的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同
本文将介绍如何在反序列化之前使用 System.Text.Json 验证 JSON的详细情况,特别是关于反序列化json数据的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于(de) 使用 System.Text.Json 序列化流、.net System.Text.Json 基于属性名称的序列化、.Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程、ASP.NET Core 3.0 System.Text.Json Camel案例序列化的知识。
本文目录一览:- 如何在反序列化之前使用 System.Text.Json 验证 JSON(反序列化json数据)
- (de) 使用 System.Text.Json 序列化流
- .net System.Text.Json 基于属性名称的序列化
- .Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程
- ASP.NET Core 3.0 System.Text.Json Camel案例序列化
如何在反序列化之前使用 System.Text.Json 验证 JSON(反序列化json数据)
如何解决如何在反序列化之前使用 System.Text.Json 验证 JSON?
在 .NET Core 5.0 中,使用 System.Text.Json.JsonSerializer Deserialize(someJsonFile) 我得到:
System.Text.Json.JsonException: ''The JSON value Could not be converted to System.Guid. Path: $.someGuid | ..
这是预期的,因为 someGuid 属性的类型为 System.Guid 并且 JSON 文件/字符串中 someGuid 的值为:
{
"someGuid": ""
}
无法正确反序列化..(因为它不是 Guid.Empty)..
我的问题。
在反序列化之前验证 Json 的好的通用实现是什么(一般而言)?像 TryParse 或 JsonDocument.Parse?当然,尝试捕捉,但这很脏(恕我直言)。
顺便说一句:我不想使用 Newtonsoft
感谢您的建议(当然还有批评者)。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
(de) 使用 System.Text.Json 序列化流
如何解决(de) 使用 System.Text.Json 序列化流?
我正在尝试使用 System.Text.Json 的 JsonSerializer 将对象序列化为 MemoryStream。我无法在文档中找到它的实现/方法。有人可以分享使用 System.Text.Json 进行序列化和反序列化的示例实现吗?
解决方法
不清楚问题出在哪里,或者缺少哪些文档和示例,因为 docs.microsoft.com
中有多个部分以及数百篇博文和文章。在文档中,JSON serialization and deserialization 是一个很好的起点,How to serialize and deserialize (marshal and unmarshal) JSON in .NET 包括 Serialize to UTF8 部分。
MemoryStream 无论如何都只是 byte[]
数组上的 Stream 包装器,因此序列化为 MemoryStream
与直接序列化为 byte[]
数组相同。这可以通过 JsonSerializer.SerializeToUtf8Bytes:
byte[] jsonUtf8Bytes =JsonSerializer.SerializeToUtf8Bytes(weatherForecast);
最后,在 .NET 中,任何需要序列化的东西都通过 Reader 和 Writer 对象工作,例如 TextReader、StreamReader、TextReader 和 -Writers。在 JSON.NET 的情况下,这是通过 Utf8JsonWriter 对象完成的。 JsonSerializer.Serialize 具有写入 Utf8JsonWriter
的重载:
using var stream=File.OpenWrite(somePath);
using var writer=new Utf8JsonWriter(stream);
JsonSerializer.Serialize(writer,myObject);
不过,这是使用 System.Text.Json
的缓慢方式。使用缓冲区意味着分配和清理它们,这很昂贵,尤其是在 Web 应用程序中。出于这个原因,ASP.NET Core 使用 IO pipelines 而不是流来接收和发送数据到套接字,使用从缓冲池租用的可重用缓冲区,并在 ASP.NET Core 管道中的每个步骤中传递。传递 byte[]
缓冲区会复制它们的内容,因此 .NET Core 引入了 Span<>
和 Memory<>
类型,它们表示现有(可能是池化的)缓冲区上的 view .这样,ASP.NET Core 会传递缓冲区的这些“视图”,而不是缓冲区本身。
System.Text.Json
旨在使用管道和可重用内存而不是流,从而允许 ASP.NET Core 在高流量网站中使用最少的内存和尽可能少的分配。 ASP.NET Core 使用 Utf8JsonWriter(IBufferWriter) 构造函数通过 PipeWriter 写入输出管道。
我们可以使用相同的重载来写入带有 ArrayBufferWriter 的可重用缓冲区。这相当于使用 MemoryStream
BUT 输出通过 ReadOnlySpan<byte>
或 Memory<byte>
访问,因此不必复制:>
using var buffer=new ArrayBufferWriter<byte>(65536);
using var writer=new Utf8JsonWriter(buffer);
JsonSerializer.Serialize(writer,myObject);
ReadOnlySpan<byte> data=buffer.WrittenSpan;
,
更好的选择是使用 newtonsoft.json。
它有很多例子
.net System.Text.Json 基于属性名称的序列化
如何解决.net System.Text.Json 基于属性名称的序列化?
是否可以编写自定义转换器以根据属性名称进行序列化?
例如,如果属性名称以“DateTime”结尾,则保留 DateTime 类型属性的时间部分,否则丢弃时间部分。 转换器应该适用于所有类型,并且只针对 DateTime 属性。
您似乎无法在 Write
的 JsonConverter<T>
方法中检查属性名称。
解决方法
是的,你可以通过反射来做到这一点。
假设您有以下数据模型:
class Example
{
public Guid Id { get; set; }
public int InternalId { get; set; }
public DateTime DateOnly { get; set; }
public DateTime DateTime { get; set; }
}
- 如您所见,我们有两个
DateTime
属性- 其中一个以
Time
结尾
- 其中一个以
- 我们还有另外两个属性只是为了确保我们 在序列化过程中不会丢失类型信息
您可以像这样针对整个对象创建一个 JsonConverter:
class ExampleConverter : JsonConverter<Example>
{
public override Example Read(ref Utf8JsonReader reader,Type typeToConvert,JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer,Example value,JsonSerializerOptions options)
{
var objectProperties = value.GetType().GetProperties();
var objectFieldNameValuePairs = new Dictionary<string,object>();
foreach (var objectProperty in objectProperties)
{
if (objectProperty.PropertyType == typeof(DateTime))
{
var datetimeFieldValue = (DateTime)objectProperty.GetValue(value);
var transformedValue = datetimeFieldValue.ToString(objectProperty.Name.EndsWith("Time") ? "g" : "d");
objectFieldNameValuePairs.Add(objectProperty.Name,transformedValue);
}
else
objectFieldNameValuePairs.Add(objectProperty.Name,objectProperty.GetValue(value));
}
writer.WriteStartObject();
foreach (KeyValuePair<string,object> fieldNameAndValue in objectFieldNameValuePairs)
{
writer.WritePropertyName(fieldNameAndValue.Key);
JsonSerializer.Serialize(writer,fieldNameAndValue.Value,options);
}
writer.WriteEndObject();
}
}
- 首先我们获取
Example
的所有属性 - 然后我们遍历它们
- 如果该属性包含
DateTime
,则根据您提供的启发式方法,我们将使用不同的 date formatting string- 否则我们不做任何转换
- 最后我们手动序列化
Dictionary
用法
var example = new Example { DateOnly = DateTime.UtcNow,DateTime = DateTime.UtcNow,Id = Guid.NewGuid(),InternalId = 100 };
var serializedExample = JsonSerializer.Serialize(example,new JsonSerializerOptions { Converters = { new ExampleConverter() } });
Console.WriteLine(serializedExample);
输出
{
"Id":"eddd0620-b27c-4041-bd28-af6bfbd70583","InternalId":100,"DateOnly":"7/23/2021","DateTime":"7/23/2021 7:10 AM"
}
更新使转换器更通用
正如评论部分所讨论的,转换器不应绑定到特定的类。它应该能够处理任何类。不幸的是,我们无法指定 object
作为 JsonConverter
的类型参数。
另一方面,当我们从转换器创建实例时,我们可以接收类型参数。所以,这是修改后的转换器代码:
class DateTimeConverter<T> : JsonConverter<T>
{
public override T Read(ref Utf8JsonReader reader,T value,JsonSerializerOptions options)
{
PropertyInfo[] props = value.GetType().GetProperties();
Dictionary<string,object> data = new Dictionary<string,object>();
foreach (var prop in props)
{
if (prop.PropertyType == typeof(DateTime))
{
var date = (DateTime)prop.GetValue(value);
data.Add(prop.Name,date.ToString(prop.Name.EndsWith("Time") ? "g" : "d"));
}
else
data.Add(prop.Name,prop.GetValue(value));
}
writer.WriteStartObject();
foreach (KeyValuePair<string,object> item in data)
{
writer.WritePropertyName(item.Key);
JsonSerializer.Serialize(writer,item.Value,options);
}
writer.WriteEndObject();
}
}
用法
var ex = new Example
{
DateOnly = DateTime.UtcNow,InternalId = 100
};
var aex = new AnotherExample
{
CreationDate = DateTime.UtcNow,Description = "Testing"
};
var options = new JsonSerializerOptions
{
Converters =
{
new DateTimeConverter<Example>(),new DateTimeConverter<AnotherExample>()
}
};
Console.WriteLine(JsonSerializer.Serialize(ex,options));
Console.WriteLine(JsonSerializer.Serialize(aex,options));
已知限制:此转换器不能用于匿名类型。
.Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程
JSON作为一种轻量级的数据交换格式,简单灵活,被很多系统用来数据交互,作为一名.NET开发人员,JSON.NET无疑是最好的序列化框架,支持XML和JSON序列化,高性能,免费开源,支持LINQ查询。目前已被微软集成于webapi框架之中,因此,熟练掌握JSON.NET相当重要,这篇文章是零度参考官网整理的示例,通过这些示例,可以全面了解JSON.NET提供的功能。
Newtonsoft.Json的地址:
官网:http://json.codeplex.com/
源码地址:https://github.com/JamesNK/Newtonsoft.Json
Newtonsoft.Json.dll下载:https://github.com/JamesNK/Newtonsoft.Json/releases
1、使用Newtonsoft.Json(JSON.NET)序列化对象,通过Newtonsoft.Json.Formatting将json格式化输出。
Account account = new Account { Email = "1930906722@qq.com",Active = true,CreatedDate =DateTime.Now,Roles = new List<string> { "User","Admin" } }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(account,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
public class Account { public string Name { get; set; } public string Email { get; set; } public bool Active { get; set; } public DateTime CreatedDate { get; set; } public IList<string> Roles { get; set; } }
执行结果:
2、使用Newtonsoft.Json(JSON.NET)序列化List集合:
List<string> videogames = new List<string> { "HTML5","JavaScript",".net","c#",".net core" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(videogames); Console.WriteLine(json);
执行结果:
3、使用Newtonsoft.Json(JSON.NET)序列化dictionary字典
System.Collections.Generic.Dictionary<string,string> dic = new System.Collections.Generic.Dictionary<string,string> { { "Name","张三" },{ "Age","20" },{ "Email","193090622@qq.com" } }; string json1 = Newtonsoft.Json.JsonConvert.SerializeObject(dic,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json1); Console.WriteLine(""); Console.WriteLine("未格式化的json:"); string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(dic,Newtonsoft.Json.Formatting.None); Console.WriteLine(json2);
执行结果:
4、Newtonsoft.Json(JSON.NET)将序列化结果保存到指定的文件:
User movie = new User { Name = "张三",Age = 1993 }; using (System.IO.StreamWriter file = System.IO.File.CreateText(@"F:\UserInfo.txt")) { Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); serializer.Serialize(file,movie); }
public class User { public string Name { set; get; } public int Age { set; get; } }
执行后保存到文件的结果:
5、Newtonsoft.Json(JSON.NET)基于枚举类型的JsonConverters转换器
List<JosnEnum> list = new List<JosnEnum> { JosnEnum.NotStartus,JosnEnum.Startus }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(list); Console.WriteLine(json); Console.WriteLine(""); System.Collections.Generic.Dictionary<string,int> dic = new System.Collections.Generic.Dictionary<string,int> { {((JosnEnum)(int)JosnEnum.NotStartus).ToString(),(int)JosnEnum.NotStartus},{((JosnEnum)(int)JosnEnum.Startus).ToString(),(int)JosnEnum.Startus} }; string dicJson = Newtonsoft.Json.JsonConvert.SerializeObject(dic); Console.WriteLine(dicJson); Console.WriteLine(""); List<JosnEnum> list2 = new List<JosnEnum> { JosnEnum.NotStartus,JosnEnum.Startus }; string json3 = Newtonsoft.Json.JsonConvert.SerializeObject(list2,new Newtonsoft.Json.Converters.StringEnumConverter()); Console.WriteLine(json3); Console.WriteLine(""); List<JosnEnum> result = Newtonsoft.Json.JsonConvert.DeserializeObject<List<JosnEnum>>(json3,new Newtonsoft.Json.Converters.StringEnumConverter()); Console.WriteLine(string.Join(",",result.Select(c => c.ToString())));
public enum JosnEnum { NotStartus = 0,Startus = 1 }
执行结果:
6、Newtonsoft.Json(JSON.NET)通过JRaw将JS函数序列化到JSON中
JavaScriptSettings settings = new JavaScriptSettings { OnLoadFunction = new Newtonsoft.Json.Linq.JRaw("OnLoad"),OnSucceedFunction = new Newtonsoft.Json.Linq.JRaw("function(e) { alert(e); }") }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(settings,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
public class JavaScriptSettings { public Newtonsoft.Json.Linq.JRaw OnLoadFunction { get; set; } public Newtonsoft.Json.Linq.JRaw OnSucceedFunction { get; set; } }
7、使用Newtonsoft.Json(JSON.NET)将json反序列化对象
string json = @"{ 'Email': '1930906722@qq.com','Active': true,'CreatedDate': '2016-11-26 20:39','Roles': [ 'User','Admin' ] }"; Account account = Newtonsoft.Json.JsonConvert.DeserializeObject<Account>(json); Console.WriteLine(account.Email);
public class Account { public string Name { get; set; } public string Email { get; set; } public bool Active { get; set; } public DateTime CreatedDate { get; set; } public IList<string> Roles { get; set; } }
执行结果:
8、使用Newtonsoft.Json(JSON.NET)反序列化List集合:
string json = @"['Html5','C#','.Net','.Net Core']"; List<string> videogames = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(json); Console.WriteLine(string.Join(",videogames));
执行结果:
9、使用Newtonsoft.Json(JSON.NET)反序列化dictionary字典
string json = @"{'Name': '张三','Age': '23'}"; var htmlAttributes = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string,string>>(json); Console.WriteLine(htmlAttributes["Name"]); Console.WriteLine(htmlAttributes["Age"]);
执行结果:
10、使用Newtonsoft.Json(JSON.NET)序列化var匿名类型,有时候,我们并不需要先定义一个类,然后new一个对象后再进行序列化,JSON.NET支持匿名类型的序列化和反序列化。
var test1 = new { Name = "李四",Age = 26 }; var json = Newtonsoft.Json.JsonConvert.SerializeObject(test1); Console.WriteLine(json); Console.WriteLine(""); var test2 = new { Name = "",Age = 0 }; string json1 = @"{'Name':'张三','Age':'25'}"; var result = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(json1,test2); Console.WriteLine(result.Name);
执行结果:
11、Newtonsoft.Json(JSON.NET)用新JSON字符串填充指定对象的属性值
Account account = new Account { Email = "1930906722@qq.com",CreatedDate = DateTime.Now,"Admin" } }; string json = @"{'Active': false,'Roles': ['Expired']}"; Newtonsoft.Json.JsonConvert.PopulateObject(json,account); Console.WriteLine(account.Active); Console.WriteLine(account.Email);
public class Account { public string Name { get; set; } public string Email { get; set; } public bool Active { get; set; } public DateTime CreatedDate { get; set; } public IList<string> Roles { get; set; } }
执行结果:
12、使用Newtonsoft.Json(JSON.NET)反序列化时可指定构造函数:
首先我们定义如下的类型,我们希望JSON.NET反序列化对象时使用第2个构造函数,我们将第一个默认构造函数屏蔽,标记为私有private修饰符。第2个构造函数需要指定一个website对象作为参数,如果提供的参数为null则抛出异常:
public class Website { public string Url { get; set; } private Website() { } public Website(Website website) { if (website == null) throw new ArgumentNullException("website"); Url = website.Url; } }
现在使用一般的方式反序列化一个JSON字符串。执行出现的结果:
我们发现该序列化方法抛出了异常,并没有按照我们预想的方式进行反序列化,JSON.NET提供如下的方式指定公有构造函数。
string json = @"{'Url':'http://www.cnblogs.com/linJie1930906722/'}"; Website website = Newtonsoft.Json.JsonConvert.DeserializeObject<Website>(json,new Newtonsoft.Json.JsonSerializerSettings { ConstructorHandling = Newtonsoft.Json.ConstructorHandling.AllowNonPublicDefaultConstructor }); Console.WriteLine(website.Url);
执行结果:
另外,JSON.NET提供了指定任何构造函数的JsonConstructorAttribute特性,只需要在构造函数上标记,即可指定构造函数。
public class Users { public string UserName { get; private set; } public bool Enabled { get; private set; } public Users() { } [Newtonsoft.Json.JsonConstructor] public Users(string userName,bool enabled) { UserName = userName; Enabled = enabled; } }
string json = @"{""UserName"": ""希特勒"",""Enabled"": true}"; Users user = Newtonsoft.Json.JsonConvert.DeserializeObject<Users>(json); Console.WriteLine(user.UserName);
执行结果:
13、当对象的属性为默认值(0或null)时不序列化该属性
public class Person { public string Name { get; set; } public int Age { get; set; } public Person Partner { get; set; } public decimal? Salary { get; set; } }
Person person1 = new Person(); string json1 = Newtonsoft.Json.JsonConvert.SerializeObject(person1,Newtonsoft.Json.Formatting.Indented,new Newtonsoft.Json.JsonSerializerSettings { DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore }); Console.WriteLine(json1); Console.WriteLine(""); Person person2 = new Person(){Name = "奥巴马"}; string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(person2,new Newtonsoft.Json.JsonSerializerSettings { DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore }); Console.WriteLine(json2);
执行结果:
14、Newtonsoft.Json(JSON.NET)中忽略null值得处理器
public class Person { public string Name { get; set; } public int Age { get; set; } public Person Partner { get; set; } public decimal? Salary { get; set; } }
Person person = new Person { Name = "张三",Age = 46 }; string jsonIncludeNullValues = Newtonsoft.Json.JsonConvert.SerializeObject(person,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(jsonIncludeNullValues); Console.WriteLine(""); string json = Newtonsoft.Json.JsonConvert.SerializeObject(person,new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }); Console.WriteLine(json);
执行结果:
15、JSON.NET中循环引用的处理方法
Employee employee1 = new Employee { Name = "张三" }; Employee employee2 = new Employee { Name = "李四" }; employee1.Manager = employee2; employee2.Manager = employee2; string json = Newtonsoft.Json.JsonConvert.SerializeObject(employee1,new Newtonsoft.Json.JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore }); Console.WriteLine(json);
public class Employee { public string Name { get; set; } public Employee Manager { get; set; } }
执行结果:
16、通过ContractResolver指定属性名首字母小写,通常,在.NET中属性采用PascalCase规则(首字母大写),在JavaScript中属性名使用CamelCase规则(首字母小写),我们希望序列化后的JSON字符串符合CamelCase规则,JSON.NET提供的ContractResolver可以设置属性名小写序列化
public class User { public string Name { set; get; } public int Age { set; get; } }
User person = new User { Name = "张三",Age =52 }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(person,new Newtonsoft.Json.JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }); Console.WriteLine(json);
执行结果:
17、JSON.NET中通过特性序列化枚举类型
public enum ProductStatus { NotConfirmed,Active,Deleted } public class Product { public string Name { get; set; } [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] public ProductStatus Status { get; set; } }
Product user = new Product { Name = @"羽绒服",Status = ProductStatus.Deleted }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(user,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
18、指定需要序列化的属性
[Newtonsoft.Json.JsonObject(Newtonsoft.Json.MemberSerialization.OptIn)] public class Categroy { //Id不需要序列化 public Guid Id { get; set; } [Newtonsoft.Json.JsonProperty] public string Name { get; set; } [Newtonsoft.Json.JsonProperty] public int Size { get; set; } }
Categroy categroy = new Categroy { Id = Guid.NewGuid(),Name = "内衣",Size = 52 }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(categroy,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
19、序列化对象时指定属性名
public class Videogame { [Newtonsoft.Json.JsonProperty("name")] public string Name { get; set; } [Newtonsoft.Json.JsonProperty("release_date")] public DateTime ReleaseDate { get; set; } }
Videogame starcraft = new Videogame { Name = "英雄联盟",ReleaseDate = DateTime.Now }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(starcraft,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
20、序列化时指定属性在JSON中的顺序
public class Personl { [Newtonsoft.Json.JsonProperty(Order = 2)] public string FirstName { get; set; } [Newtonsoft.Json.JsonProperty(Order = 1)] public string LastName { get; set; } }
Personl person = new Personl { FirstName = "张三",LastName = "李四" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(person,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
21、反序列化指定属性是否必须有值必须不为null,在反序列化一个JSON时,可通过JsonProperty特性的required指定反序列化行为,当反序列化行为与指定的行为不匹配时,JSON.NET将抛出异常,required是枚举,required.Always表示属性必须有值切不能为null,required.AllowNull表示属性必须有值,但允许为null值。
public class Order { [Newtonsoft.Json.JsonProperty(required = Newtonsoft.Json.required.Always)] public string Name { get; set; } [Newtonsoft.Json.JsonProperty(required = Newtonsoft.Json.required.AllowNull)] public DateTime? ReleaseDate { get; set; } }
string json = @"{ 'Name': '促销订单','ReleaseDate': null }"; Order order = Newtonsoft.Json.JsonConvert.DeserializeObject<Order>(json); Console.WriteLine(order.Name); Console.WriteLine(order.ReleaseDate);
执行结果:
22、通过特性指定null值忽略序列化
public class Vessel { public string Name { get; set; } [Newtonsoft.Json.JsonProperty(NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public DateTime? launchdate { get; set; } }
Vessel vessel = new Vessel { Name = "张三" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(vessel,Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
执行结果:
23、忽略不需要序列化的属性,并不是对象所有属性都要参与序列化,我们可以使用JsonIgnore特性排除不需要序列化的属性,下面示例中的PasswordHash将被忽略。
public class Accounts { public string FullName { get; set; } public string EmailAddress { get; set; } [Newtonsoft.Json.JsonIgnore] public string PasswordHash { get; set; } }
Accounts account = new Accounts { FullName = "admin",EmailAddress = "1930906722@qq.com",PasswordHash = "dfsfgerhtyhsasdhjyujtgwe454811sfsg8d" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(account); Console.WriteLine(json);
执行结果:
24、序列化或反序列化时指定日期时间格式,JSON.NET中提供一个名为JsonSerializerSettings的设置对象,可通过此对象设置很多序列化和反序列化的行为,如果要设置JSON.NET序列化输出的日期时间格式,只需要指定格式化字符串即可。通过JsonSerializerSettings的DateFormatString属性指定日期时间格式:
public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public DateTime CreateDate { get; set; } }
Customer custom = new Customer { FirstName = "张三",LastName = "李四",CreateDate = DateTime.Now }; Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatString = "yyyy-MM-dd HH:mm:ss",Formatting = Newtonsoft.Json.Formatting.Indented }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(custom,settings); Console.WriteLine(json);
执行结果:
ASP.NET Core 3.0 System.Text.Json Camel案例序列化
在ASP.NET Core 3.0 Web
API项目中,如何指定System.Text.Json序列化选项以自动将Pascal
Case属性序列化/反序列化为Camel Case,反之亦然?
给定具有Pascal Case属性的模型,例如:
public class Person
{
public string Firstname { get; set; }
public string Lastname { get; set; }
}
以及使用System.Text.Json将JSON字符串反序列化为Person
类类型的代码:
var json = "{\"firstname\":\"John\",\"lastname\":\"Smith\"}";
var person = JsonSerializer.Deserialize<Person>(json);
除非将JsonPropertyName与以下每个属性一起使用,否则不会成功反序列化:
public class Person
{
[JsonPropertyName("firstname")
public string Firstname { get; set; }
[JsonPropertyName("lastname")
public string Lastname { get; set; }
}
我在中尝试了以下方法startup.cs
,但在仍然需要方面没有帮助JsonPropertyName
:
services.AddMvc().AddJsonOptions(options =>
{
options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});
// also the following given it's a Web API project
services.AddControllers().AddJsonOptions(options => {
options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});
如何使用新的System.Text.Json命名空间在ASP.NET Core 3.0中设置Camel Case序列化/反序列化?
谢谢!
关于如何在反序列化之前使用 System.Text.Json 验证 JSON和反序列化json数据的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于(de) 使用 System.Text.Json 序列化流、.net System.Text.Json 基于属性名称的序列化、.Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程、ASP.NET Core 3.0 System.Text.Json Camel案例序列化的相关知识,请在本站寻找。
本文标签: