对属性的 Json DeserializeObject 运行转换

running a transformation on a Json DeserializeObject for a property(对属性的 Json DeserializeObject 运行转换)

本文介绍了对属性的 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 运行转换

基础教程推荐