running a transformation on a Json DeserializeObject for a property(对属性的 Json DeserializeObject 运行转换)
问题描述
假设一个json字符串如下:
Assuming a json string like the following:
string json = '{"string_property":"foo_bar", ... other objects here ...}';
我想知道是否有一种方法可以对解析的对象运行转换,以便在运行以下方法后得到 foo_bar
而不是获取 foo_bar
(可以是任何东西)
I was wondering if there's a way to run a transformation on the parsed object so that instead of getting foo_bar
, I'll get foo bar
after running the following method (can be anything really)
public string Transform(string s) {
return s.Replace("_"," ");
}
我可以在反序列化后手动更改我的 poco,但想知道什么是更清洁"的方法?
I can manually alter my poco after deserializing, but wondered what would be a "cleaner" approach?
推荐答案
您可以在反序列化根对象时转换您的 string
属性,方法是使用 自定义 JsonConverter
针对所有字符串类型值:
You can transform your string
properties as you deserialize your root object by using a custom JsonConverter
targeted at all string type values:
public class ReplacingStringConverter : JsonConverter
{
readonly string oldValue;
readonly string newValue;
public ReplacingStringConverter(string oldValue, string newValue)
{
if (string.IsNullOrEmpty(oldValue))
throw new ArgumentException("string.IsNullOrEmpty(oldValue)");
if (newValue == null)
throw new ArgumentNullException("newValue");
this.oldValue = oldValue;
this.newValue = newValue;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var s = (string)JToken.Load(reader);
return s.Replace(oldValue, newValue);
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
然后像这样使用它:
var settings = new JsonSerializerSettings { Converters = new[] { new ReplacingStringConverter("_", "") } };
var result = JsonConvert.DeserializeObject<RootObject>(json, settings);
但是请注意,如果单个字符串类型属性有自己的转换器,则直接使用 [JsonConverter(Type)]
,这些转换器将优先于 ReplacingStringConverter 使用.com/json/help/html/P_Newtonsoft_Json_JsonSerializerSettings_Converters.htm" rel="nofollow noreferrer">转换器
列表.
Note however that if individual string-type properties have their own converters applied directly with [JsonConverter(Type)]
, those converters will be used in preference to the ReplacingStringConverter
in the Converters
list.
这篇关于对属性的 Json DeserializeObject 运行转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对属性的 Json DeserializeObject 运行转换
- 在 C# 中异步处理项目队列 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 使用 rss + c# 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01