本文介绍了RestSharp - 使用无效的键名反序列化 json 响应(包含句点)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been stuck on this for awhile. I have a JSON response sending me keys that include periods. For example: "cost_center.code"

如何将其放入我的对象中?我没有收到任何错误,但该值只是作为 null 传入,并且没有被反序列化到我的类中.

How can I get this into my object? I'm not getting any errors but the value is just coming in as null and isn't being deserialized into my class.

这是我的课程:

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 响应:

Here's the JSON response:

{
  "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 的容器问题吗?

I've tried both with and without the DeserializeAs. I'm not sure its even working. Am I using this property incorrectly? Is it a container issue with the List?

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

Edited and accepted the answer below to use JsonProperty. For others who may come along this was the solution.

添加了 JSON.net nuget.

Added JSON.net nuget.

using Newtonsoft.Json;

按照描述设置 JsonProperty:

Set the JsonProperty as described:

[JsonProperty("cost_center.code")]

将我的执行更改为:

var response = client.Execute(request);

然后像这样反序列化它:

Then deserialized it like this:

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

之后我可以访问该值:

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

推荐答案

对名称中带有句点的属性执行以下操作:

Do the following with properties having period in their names :

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

应该可以

这篇关于RestSharp - 使用无效的键名反序列化 json 响应(包含句点)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-01 05:26