ben*_*der 5 c# serialization json restsharp
我已经坚持了一段时间。我有一个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; }
}
Run Code Online (Sandbox Code Playgroud)
这是JSON响应:
{
"result": [
{
"company": "My Company",
"first_name": "First",
"email": "example@fakeaddress.com",
"employee_id": "123456789",
"last_name": "Last",
"cost_center.code": "12345"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我执行:
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);
Run Code Online (Sandbox Code Playgroud)
我已经尝试过有和没有DeserializeAs。我不确定它是否还能正常工作。我使用此属性不正确吗?列表是否有容器问题?
编辑并接受以下答案以使用JsonProperty。对于其他可能会遇到的人,这是解决方案。
添加了JSON.net nuget。
using Newtonsoft.Json;
Run Code Online (Sandbox Code Playgroud)
按如下所述设置JsonProperty:
[JsonProperty("cost_center.code")]
Run Code Online (Sandbox Code Playgroud)
将我的执行更改为:
var response = client.Execute(request);
Run Code Online (Sandbox Code Playgroud)
然后像这样反序列化它:
var jsonResponse = JsonConvert.DeserializeObject<RootObject>(response.Content);
Run Code Online (Sandbox Code Playgroud)
之后,我可以访问该值:
Console.WriteLine(jsonResponse.result[0].CostCenter
Run Code Online (Sandbox Code Playgroud)
小智 2
对名称中包含句点的属性执行以下操作:
[JsonProperty("cost_center.code")]
public string CostCenter{ get; set; }
Run Code Online (Sandbox Code Playgroud)
应该有效