假设一个像下面这样的 json 字符串:
string json = '{"string_property":"foo_bar", ... other objects here ...}';
我想知道是否有一种方法可以对已解析的对象运行转换,这样我就可以在运行以下方法后得到 foo_bar
而不是 foo_bar
(真的可以是任何东西)
public string Transform(string s) {
return s.Replace("_"," ");
}
我可以在反序列化后手动更改我的 poco,但想知道什么是“更清洁”的方法?
最佳答案
您可以在反序列化根对象时使用 custom JsonConverter
转换您的 string
属性针对所有字符串类型值:
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)]
,将优先使用这些转换器而不是 Converters
中的 ReplacingStringConverter
列表。
关于c# - 对属性的 Json DeserializeObject 运行转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38351661/