Serialize/Deserialize dynamic property name using JSON.NET(使用 JSON.NET 序列化/反序列化动态属性名称)
问题描述
我有以下课程:
public class MyRequest
{
public string Type {get;set;}
public string Source {get;set;}
}
我想从名为 Type 的 JSON 字段中序列化/反序列化 Source 的值,例如:
I would like to serialize/deserialize the value for Source from the JSON field named the value of Type, for example:
{
"type": "bank",
"bank": "Some value"
}
或
{
"type": "card",
"card": "Some value"
}
两者都绑定到 Source 属性.
Where both bind to the Source property.
推荐答案
你可以创建一个自定义 JsonConverter 处理动态属性名:
You could create a custom JsonConverter to handle the dynamic property name:
public class MyRequestConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(MyRequest);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
string type = (string)jo["type"];
MyRequest req = new MyRequest
{
Type = type,
Source = (string)jo[type ?? ""]
};
return req;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
MyRequest req = (MyRequest)value;
JObject jo = new JObject(
new JProperty("type", req.Type),
new JProperty(req.Type, req.Source));
jo.WriteTo(writer);
}
}
要使用转换器,请向您的类添加 [JsonConverter] 属性,如下所示:
To use the converter, add a [JsonConverter] attribute to your class like this:
[JsonConverter(typeof(MyRequestConverter))]
public class MyRequest
{
public string Type { get; set; }
public string Source { get; set; }
}
这是一个有效的往返演示:https://dotnetfiddle.net/o7NDTV
Here is a working round-trip demo: https://dotnetfiddle.net/o7NDTV
这篇关于使用 JSON.NET 序列化/反序列化动态属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 JSON.NET 序列化/反序列化动态属性名称
基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
