c# – RestSharp – 使用无效的密钥名称反序列化json响应(包含句点)

我已经坚持了一段时间.我有一个
JSON响应,向我发送包含句点的密钥.例如:“cost_center.code”

我怎样才能把它变成我的对象?我没有收到任何错误,但是这个值只是作为null而没有被反序列化到我的班级中.

这是我的课程:

public class Result
{
    public string company { get; set; }
    public string first_name { get; set; }
    public string email { get; set; }
    public string employee_id { get; set; }
    public string last_name { get; set; }
    [DeserializeAs(Name="cost_center.code")]
    public string cost_center { get; set; }
}

public class RootObject
{
    public List<Result> result { get; set; }
}

这是JSON响应:

{
  "result": [
    {
      "company": "My Company",
      "first_name": "First",
      "email": "example@fakeaddress.com",
      "employee_id": "123456789",
      "last_name": "Last",
      "cost_center.code": "12345"
    }
  ]
}

我执行:

var response = client.Execute<List<RootObject>>(request);
// this returns null
Console.WriteLine(response.Data[0].result[0].cost_center);
// all other values return fine ex:
Console.WriteLine(response.Data[0].result[0].company);

无论有没有DeserializeAs,我都试过了.我不确定它是否正常工作.我错误地使用了这个属性吗?这是List的容器问题吗?

编辑并接受以下答案以使用JsonProperty.对于其他可能出现的人来说,这就是解决方案.

添加了JSON.net nuget.

using Newtonsoft.Json;

按照描述设置JsonProperty:

[JsonProperty("cost_center.code")]

将执行更改为:

var response = client.Execute(request);

然后像这样反序列化:

var jsonResponse = JsonConvert.DeserializeObject<RootObject>(response.Content);

之后我可以访问该值:

Console.WriteLine(jsonResponse.result[0].CostCenter

最佳答案 使用名称中包含句点的属性执行以下操作:

[JsonProperty("cost_center.code")]
public string CostCenter{ get; set; }

它应该工作

点赞