Azure Table 存储中 Table 实体的序列化属性

Serialization attributes on TableEntity in Azure Table Storage

我正在使用 Web API 将 return 数据存储在 Azure table 中。我 returning 一个 class,我在 class 中继承了 TableEntity 并添加了属性,但想保持大写 属性 名称的 .Net 约定,但也保持JavaScript/json 小写属性名称的约定。

我试过将 Json.net 属性 属性添加到 class 但它似乎被忽略了。例如:

[JsonProperty("id")] public 字符串 ID {get;set;}

如果实例在 ID 上设置了值,则在序列化结果中表示 null。

根据您的描述,我在我这边测试了这个问题,发现它在我这边和 Azure 上运行良好。下面是我的详细步骤,大家可以参考一下

在 Web API 应用程序中使用 Get 函数创建一个名为 UserInfoController 的控制器,如下所示:

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

实体

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

结果

将WebAPI应用程序部署到Azure,然后通过Fiddler调用函数可以得到如下结果

综上所述,请尝试检查您使用的 Json.NET 版本。如果您使用的不是最新版本 (9.0.1),请尝试升级到最新版本并再次 运行 您的应用程序以查看它是否可以按预期运行。

仅供参考 - 虽然这没有直接回答如何让 TableEntity 遵守 JSON.net 属性......我能够通过覆盖继承的 ReadEntity 和 WriteEntity 方法来解决用例class:

例如

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