将枚举映射到json属性

时间:2019-02-12 01:53:45

标签: 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;
    }
}

1 个答案:

答案 0 :(得分:3)

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

[JsonProperty(nameof(InstrumentConfig.LowDiskpace))]

如果尝试使用此方法,并收到类似Compilation error: The name 'nameof' does not exist in the current context的错误,则表示您没有使用当前的编译器。 nameof关键字是在C#6.0 / Visual Studio 2015中引入的,只要是新的关键字都可以。

相关问题