我已经被困在这个问题上有一段时间了。我有一个 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": "[email protected]",
"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 。我不确定它是否有效。我是否错误地使用了该属性?这是列表的容器问题吗?
编辑并接受下面的答案以使用 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