对属性的 Json DeserializeObject 运行转换

3

本文介绍了对属性的 Json DeserializeObject 运行转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

假设一个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 运行转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14