Crick3t
Crick3t

Reputation: 1151

Deserialize JSon with RestSharp where the name starts with an @

I have a json response from an API that returns back with a name value where which starts with an @.

For example:

{
  "@id": "Something",
  "url": "www.example.com",
  "username": "Bob",
}

I am trying to load this with the generic GetAsync method into an object like:

RestClient restClient = new RestClient("https://api.somewebsite.com/pub");
var request = new RestRequest($"user/Bob");
var actUser = await restClient.GetAsync<User>(request)

This is working fine for all name/value pairs, but I cannot get RestSharp to initialize @id.

In my User class I have tried:

public string id { get; set; } 

and

[JsonProperty("id")]
public string ID { get; set; } 

and

[JsonProperty("@id")]
public string ID { get; set; } 

but it is always null.

Is there a way to get the @id value?

Upvotes: 1

Views: 633

Answers (1)

Serge
Serge

Reputation: 43860

try this, it works for me

using Newtonsoft.Json;

var restResponse = await restClient.ExecuteTaskAsync(request);
User user = JsonConvert.DeserializeObject<User>( restResponse.Content);

public class User
{
    [JsonProperty("@id")]
    public string Id { get; set; }
    public string url { get; set; }
    public string username { get; set; }
}

I think GetAsync uses Text.Json so you can try

    [JsonPropertyName("@id")]
    public string Id { get; set; }

but IMHO ExecuteTaskAsync is more flexible since you can use any Newtonsoft.Json or System.Text.Json options.

Upvotes: 3

Related Questions