RestSharp 108含保留字的JSON映射C#类问题及解决方法
RestSharp 108 版本JSON反序列化映射问题解决
六年前基于低于108版本的RestSharp实现了JSON到C#类的映射,用于处理包含空格和保留字的字段。升级到RestSharp 108版本后,出现以下错误:
无法从程序集'RestSharp, Version=108.0.1.0, Culture=neutral, PublicKeyToken=598062e77f915f75'加载类型'RestSharp.Deserializers.DeserializeAsAttribute'
相关代码与数据
JSON载荷
{ "agentType": "Sub Broker", "agentCode": "FWM", "agentName": "FWM", "default": "Y" }
旧版C#类(依赖RestSharp的DeserializeAsAttribute)
public class AgentInformation { public string agentType { get; set; } public string agentCode { get; set; } public string agentName { get; set; } [DeserializeAs(Name = "default")] public string isDefault { get; set; } }
升级后仍用旧写法的调用代码(触发报错)
try { var client = new RestClient("https://xxxx.io/v3/xxxxxxx"); var request = new RestRequest(); request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; }; var response = client.Get<AgentInformation>(request); var data = response; Console.ReadLine(); } catch (Exception er) { throw er; }
解决方案
RestSharp 108移除了DeserializeAsAttribute,改用System.Text.Json的JsonPropertyName特性实现字段映射,具体调整如下:
修改后的C#类
public class AgentInformation { public string agentType { get; set; } public string agentCode { get; set; } public string agentName { get; set; } [JsonPropertyName("default")] public string isDefault { get; set; } }
调整后的API调用代码
try { var client = new RestClient("https://xxx.xxx.io/v3/xxxx-xxx-xxxx-xxx-xxxxx"); var request = new RestRequest(); request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; }; var response = await client.GetAsync(request); var options = new JsonSerializerOptions(JsonSerializerDefaults.Web); var data = JsonSerializer.Deserialize<Model.AgentInformation>(response.Content, options); Console.WriteLine(data.isDefault); } catch (Exception er) { throw er; }
内容的提问来源于stack exchange,提问作者hiFI
相关产品推荐
相关产品推荐

