Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 374
BryanJ Avatar asked Oct 30 '22 17:10

BryanJ


1 Answers

Do the following with properties having period in their names :

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

It should work

like image 135
Kayani Avatar answered Nov 09 '22 15:11

Kayani