5

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

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.

Here's my classes:

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; }
}

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"
    }
  ]
}

I execute with:

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);

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?


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

Added JSON.net nuget.

using Newtonsoft.Json;

Set the JsonProperty as described:

[JsonProperty("cost_center.code")]

Changed my execute to:

var response = client.Execute(request);

Then deserialized it like this:

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

Afterwards I can access the value:

Console.WriteLine(jsonResponse.result[0].CostCenter
BryanJ
  • 213
  • 2
  • 7
  • Possible duplicate of [RestSharp Serialize/Deserialize Naming Conversion](http://stackoverflow.com/questions/30037387/restsharp-serialize-deserialize-naming-conversion) – dbc Oct 08 '15 at 07:55

2 Answers2

2

Do the following with properties having period in their names :

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

It should work

Kayani
  • 942
  • 7
  • 23
0

If you want to user RestSharp natively or couldn't get the Newtonsoft.Json.JsonSerializer support to work (which I couldn't), they just added support for proper deserialization of properties with dots in their names as of 106.1.0.

See my response here: Accessing properties with a dot in their name

James Eby
  • 1,784
  • 20
  • 25