将枚举映射到 json 属性

nik*_*hil 1 c# json.net

我有一个名为 InstrumentConfigValues 的类,其属性具有实现接口的类型。现在我有一个名为 InstrumentConfig 的枚举,它具有一组值。这些值就像 json 文件中的键。我想映射类似[JsonProperty(InstrumentConfig.LowDiskpace.ToString()].

出于某种原因,它不允许这样做并抱怨说:

属性参数必须是常量表达式

我特别提到了许多帖子JsonStringEnumConverter。但是如何使用枚举键映射每个属性。我也看到了这篇文章JsonSerializationSettings但无法与我的问题相关联。请帮忙/

public class InstrumentConfigValues : IInstrumentConfig
{      
    public double SpaceNeededForSingleRun
    {
        get; set;
    }

    public int NumberOfInputSlots
    {
        get; set;
    }

    public int SupportedChannelCount
    {
        get; set;
    }
}

//I want this inheritance as some other class wants to access the values.
public abstract class InstrumentConfigReadWrite : InstrumentConfigValues
{
    protected ReturnCodes PopulateValuesFromJObject(JObject jObject, string path)
    {
        try
        {
            if (JsonConvert.DeserializeObject<InstrumentConfigValues>(jObject.ToString()) == null)
            {
                return ReturnCodes.ErrorReadingFile;
            }
        }
        catch (JsonSerializationException jex)
        {
            SystemDebugLogLogger.LogException(jex, "Invalid Instrument Config File Values. Data needs to be copied over.");
            return ReturnCodes.ErrorReadingFile;
        }
        return ReturnCodes.Success;
    }
}
Run Code Online (Sandbox Code Playgroud)

xan*_*der 5

只要您使用的是当前编译器,就可以使用nameof.

[JsonProperty(nameof(InstrumentConfig.LowDiskpace))]
Run Code Online (Sandbox Code Playgroud)

如果您尝试使用它,并得到类似 的错误Compilation error: The name 'nameof' does not exist in the current context,则意味着您没有使用当前的编译器。该nameof关键字是在 C# 6.0/Visual Studio 2015 中引入的——任何比它更新的都应该没问题。