System.Text.Json中的等效类型-- JsonClassInfo
和 JsonPropertyInfo
-- 都是内部的。有一个开放性增强请求System.Text.Json中DefaultContractResolver的等效项#31257,要求提供公共等效项。 - dbc Nov 25 at 19:11
Github问题:
请尝试以下操作:
我编写了一个扩展程序,以提供缺失的功能:https://github.com/dahomey-technologies/Dahomey.Json。
您将找到对编程对象映射的支持。
定义自己的 IObjectMappingConvention 实现:
public class SelectiveSerializer : IObjectMappingConvention
{
private readonly IObjectMappingConvention defaultObjectMappingConvention = new DefaultObjectMappingConvention();
private readonly string[] fields;
public SelectiveSerializer(string fields)
{
var fieldColl = fields.Split(',');
this.fields = fieldColl
.Select(f => f.ToLower().Trim())
.ToArray();
}
public void Apply<T>(JsonSerializerOptions options, ObjectMapping<T> objectMapping) where T : class
{
defaultObjectMappingConvention.Apply<T>(options, objectMapping);
foreach (IMemberMapping memberMapping in objectMapping.MemberMappings)
{
if (memberMapping is MemberMapping<T> member)
{
member.SetShouldSerializeMethod(o => fields.Contains(member.MemberName.ToLower()));
}
}
}
}
定义你的类:
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
通过在 JsonSerializerOptions 上调用 Dahomey.Json 命名空间中定义的扩展方法 SetupExtensions,设置 json 扩展。
JsonSerializerOptions options = new JsonSerializerOptions();
options.SetupExtensions();
为该类注册新的对象映射约定:
options.GetObjectMappingConventionRegistry().RegisterConvention(
typeof(Employee), new SelectiveSerializer("FirstName,Email,Id"));
然后使用常规的Sytem.Text.Json API对您的类进行序列化:
Employee employee = new Employee
{
Id = 12,
FirstName = "John",
LastName = "Doe",
Email = "john.doe@acme.com"
};
string json = JsonSerializer.Serialize(employee, options);
Newtonsoft
迁移到System.Text.Json
?实际上,net core 3.0 可以支持Newtonsoft
。那你的代码是如何工作的呢?它用于将请求体数据转换为小写吗? - RenaSystem.Text.Json
中的等效类型 --JsonClassInfo
和JsonPropertyInfo
-- 是 internal 的。有一个开放的增强请求 Equivalent of DefaultContractResolver in System.Text.Json #42001,要求提供一个公共的等效类型。 - dbc