csharp JSON自定义字段合同解析器
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp JSON自定义字段合同解析器相关的知识,希望对你有一定的参考价值。
using System;
using System.Collections.Generic;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class Program
{
public static void Main()
{
string content = @"{
""id"": 1,
""child"": {
""field1"": ""testing"",
""field2"": ""another string"",
""CustomFieldCustomer"": ""Customer Name"",
""CustomFieldAssets"": [""asset1"", ""asset2"", ""asset3""]
}
}";
var contractResolver = new FieldMappingContractResolver
{
FieldMappings =
new Dictionary<string, string>() {{"Assets", "CustomFieldAssets"}, {"Customer", "CustomFieldCustomer"}}
};
var result = (Root)JsonConvert.DeserializeObject(content, typeof(Root), new JsonSerializerSettings { ContractResolver = contractResolver });
Console.WriteLine("id: {0}", result.id);
Console.WriteLine("child.field1: {0}", result.child.field1);
Console.WriteLine("child.field2: {0}", result.child.field2);
Console.WriteLine("child.Customer: {0}", result.child.Customer);
Console.WriteLine("child.Assets.Count: {0}", result.child.Assets.Count);
}
}
public class Root
{
public int id { get; set; }
public Child child { get; set; }
}
public class Child
{
public dynamic field1 { get; set; }
public string field2 { get; set; }
public string Customer { get; set; }
public List<string> Assets { get; set; }
public Child()
{
Assets = new List<string>();
}
}
public class FieldMappingContractResolver : DefaultContractResolver
{
public Dictionary<string, string> FieldMappings;
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (FieldMappings.ContainsKey(property.PropertyName))
property.PropertyName = FieldMappings[property.PropertyName];
return property;
}
}
以上是关于csharp JSON自定义字段合同解析器的主要内容,如果未能解决你的问题,请参考以下文章
SignalR .NET Core camelCase JSON 合同解析器
无法替换 ASP.Core 3 中的默认 JSON 合同解析器
csharp #JSON解析器MBAD MPBA
Python3自定义json逐层解析器
Jackson - 自定义反序列化器不会读取 JSON 中的所有字段
如何为计时时间戳使用自定义 serde 反序列化器?