0
votes

Im using web API to return data in azure table storage. Im returning a class that I 'm inheriting TableEntity in a class and adding properties but want to keep to the .Net convention of capitalized property names but also keep to the JavaScript/json convention of lowercase properties names.

I've tried adding the Json.net property attributes to the class but it appears to be ignored. E.g.:

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

If the instance has a value set on ID, null is represent in the serialized result.

2

2 Answers

0
votes

According to your description, I tested this issue on my side and found it works well on my side and Azure. Here is my detailed steps, you could refer to it.

Create a controller named UserInfoController in the Web API application with the Get function like this:

// GET: api/UserInfo
[HttpGet]
public async Task<string> Get()
{
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(<your-Storage-ConnectionString>);
    CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
    CloudTable cloudTable = tableClient.GetTableReference("UserInfo");
    TableQuery<User> query = new TableQuery<User>()
        .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "Grade Four"));
    var results =await cloudTable.ExecuteQuerySegmentedAsync(query, null);
    //Serialize the object to string by using the latest stable version of Newtonsoft.Json
    string jsonString = JsonConvert.SerializeObject(results);
    return jsonString;
}

Entity

public class User : TableEntity
{
    public User(string partitionKey, string rowKey)
    {
        this.PartitionKey = partitionKey;
        this.RowKey = rowKey;
    }
    public User() { }

    [JsonProperty("id")]
    public long ID { get; set; }
    [JsonProperty("username")]
    public string UserName { get; set; }
    [JsonProperty("phone")]
    public string Phone { get; set; }
    [JsonProperty("age")]
    public int Age { get; set; }
}

Result

Deploy the Web API application to Azure, then you could find the following result by calling the function via Fiddler.

In summary, please try to check the version of Json.NET you are using. If you aren't using the latest (9.0.1), then please try to upgrade to the latest version and run your application again to find whether it could work as expected.

0
votes

FYI - while this doesn't answer the direct answer of how to get TableEntity to respect JSON.net attributes... I was able to solve the use case by overriding the ReadEntity and WriteEntity method in the inherited class:

e.g.

public class User : TableEntity{
   //Upper case name
   public string Name {get; set};
   public override void ReadEntity(IDictionary<string, AzureTableStorage.EntityProperty> properties, OperationContext operationContext){
       base.ReadEntity(properties, operationContext);
       //lower case
       this.Name = properties["name"];
   }