我正在编写一些代码,以使用RestSharp和JSON.net库从API收集数据。直到最近我的模型开始恢复为空(这对我的知识没有任何更改)之前,这一直很好。查询的内容具有信息,因此它不应为空对象。结果显示为空。
下面是我如何进行转换的摘要示例:
IRestResponse summaryResponse = summaryClient.Execute(summaryRequest);
RootobjectSummary result = JsonConvert.DeserializeObject<RootobjectSummary>(summaryResponse.Content);
return result;
下面是上面使用的模型:
public class RootobjectSummary
{
public InsuranceSummary InsuranceSummary { get; set; }
}
public class InsuranceSummary
{
public int InsuredTenantsCount { get; set; }
public int NewPoliciesCount { get; set; }
public int CancelledPoliciesCount { get; set; }
public float PercentageOfTenantsInsured { get; set; }
public float CoverageTotal { get; set; }
public float PaymentTotal { get; set; }
public float RefundTotal { get; set; }
public float NetPaymentAmount { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
}
最后,这是我得到的应该转换的JSON响应:
"{\"insurance_summary\":{\"insured_tenants_count\":7,\"new_policies_count\":7,\"cancelled_policies_count\":0,\"percentage_of_tenants_insured\":13.20754716981132,\"coverage_total\":130000.0,\"payment_total\":0.0,\"refund_total\":0.0,\"net_payment_amount\":0.0,\"start_date\":\"2018-07-03\",\"end_date\":\"2018-07-03\",\"facility_policy_number\":\"ABC12345\",\"master_policy_number\":\"CBA54321\"},\"meta\":{\"status_code\":200,\"status_message\":\"OK\",\"status_cat\":\"https://http.cat/200\",\"request_method\":\"GET\",\"request_id\":\"5a598888-eab3-4fab-9474-8856418f506b\",\"parameters\":{\"CreatedAfter\":\"2017-01-01-01T00:00:00-07:00\",\"CreatedBefore\":\"2018-07-01T00:00:00-07:00\",\"oauth_consumer_key\":\"GVelfUpJTn2NqGNf1bwJTbVTl5MDdHp3uTXyDaCd\",\"oauth_nonce\":\"9072365\",\"oauth_signature_method\":\"PLAINTEXT\",\"oauth_timestamp\":\"1530632568\",\"oauth_version\":\"1.0\",\"oauth_signature\":\"TRDNYFta6z8zNwE5lFCErnShnYLEvsFebz0wPRdy\\u0026\",\"facility_id\":\"b2af724f-3af4-4d62-94e4-88211763d18e\"}}}"
答案 0 :(得分:2)
您必须配置反序列化器以使用蛇形案例命名:
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
RootobjectSummary result = JsonConvert.DeserializeObject<RootobjectSummary>(summaryResponse.Content, new JsonSerializerSettings
{
ContractResolver = contractResolver
});