我收到包含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反序列化器,但即使实现自定义反序列化器,我也不知道如何以不同的方式将一个值反序列化为其他所有值。
答案 0 :(得分:2)
目前还不清楚为什么要使用RestSharp对服务器上的请求进行反序列化,JSON.NET通常可以很好地处理这个问题。
例如,如果您有以下类:
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);