使用 RestSharp 反序列化 json 时将 int 转换为 bitmask/flags

Convert int to bitmask/flags when deserializing json wtih RestSharp

我收到包含 32 位整数的 REST 请求。我想根据以下枚举将其转换为一组标志:

[Flags]
public enum TowerStatus
{
    NotUsed = 4194304,
    DireAncientTop = 2097152,
    DireAncientBottom = 1048576,
    DireBottomTier3 = 524288,
    DireBottomTier2 = 262144,
    DireBottomTier1 = 131072,
    DireMiddleTier3 = 65536,
    DireMiddleTier2 = 32768,
    DireMiddleTier1 = 16384,
    DireTopTier3 = 8192,
    DireTopTier2 = 4096,
    DireTopTier1 = 2048,
    RadiantAncientTop = 1024,
    RadiantAncientBottom = 512,
    RadiantBottomTier3 = 256,
    RadiantBottomTier2 = 128,
    RadiantBottomTier1 = 64,
    RadiantMiddleTier3 = 32,
    RadiantMiddleTier2 = 16,
    RadiantMiddleTier1 = 8,
    RadiantTopTier3 = 4,
    RadiantTopTier2 = 2,
    RadiantTopTier1 = 1
}

但我不确定如何尝试将 int 反序列化为 CLR 对象。

我正在使用 RestSharp 提供的默认 JSON 反序列化器,但即使实现自定义反序列化器,我也不知道如何以不同的方式将一个值反序列化为其他所有值。

不清楚为什么要使用 RestSharp 反序列化服务器上​​的请求,JSON.NET 通常可以很好地处理这个问题。

例如,如果您有以下 class:

public class MyModel
{
    public TowerStatus Foo { get; set; }
}

和以下 JSON 输入:

string json = "{\"Foo\": 393216 }";

您可以将其反序列化回模型,枚举标志将得到尊重:

var model = JsonConvert.DeserializeObject<MyModel>(response);
Console.WriteLine(model.Foo);
// prints DireBottomTier1, DireBottomTier2

如果出于某种原因您需要使用 RestSharp 进行反序列化,那么您可以编写自定义反序列化程序:

public class RestSharpJsonNetDeserializer : IDeserializer
{
    public RestSharpJsonNetDeserializer()
    {
        ContentType = "application/json";
    }

    public T Deserialize<T>(IRestResponse response)
    {
        return JsonConvert.DeserializeObject<T>(response.Content);
    }

    public string DateFormat { get; set; }
    public string RootElement { get; set; }
    public string Namespace { get; set; }
    public string ContentType { get; set; }
}

可以这样使用:

string json = "{\"Foo\": 393216 }";
var response = new RestResponse();
response.Content = json;
var deserializer = new RestSharpJsonNetDeserializer();
var model = deserializer.Deserialize<MyModel>(response);