BryanJ
BryanJ

Reputation: 213

RestSharp - deserialize json response with invalid key name (contains a period )

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": "[email protected]",
      "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

Upvotes: 5

Views: 1799

Answers (2)

James Eby
James Eby

Reputation: 1784

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

Upvotes: 0

Kayani
Kayani

Reputation: 972

Do the following with properties having period in their names :

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

It should work

Upvotes: 2

Related Questions