2016-09-17 57 views
0

使用Web API在Azure表存储中返回数据。我返回一个类,我在一个类中继承TableEntity并添加属性,但希望保留大写属性名称的.Net约定,但也要遵守小写属性名称的JavaScript/json约定。Azure表中的TableEntity中的序列化属性存储

我已经尝试将Json.net属性属性添加到类,但它似乎被忽略。例如为:

[JsonProperty( “ID”)] 公共字符串ID {得到;集;}

如果实例对ID设置的值,零是表示在序列化结果。

回答

0

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

eg

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

根据你的描述,我在我身边测试了这个问题,发现它适合我和Azure。这是我详细的步骤,你可以参考它。

创建一个名为UserInfoController在Web API应用与Get功能像这样的控制器:

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

结果

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

实体将Web API应用程序部署到Azure,然后通过Fiddler调用该函数,可以找到以下结果。

总之,请尝试检查您正在使用的Json.NET的版本。如果您没有使用最新版本(9.0.1),请尝试升级到最新版本并再次运行您的应用程序,以确定它是否可以按预期工作。

+0

嗯,我想我可以返回类型更改为字符串,但因为其他内部操作直接调用的函数,如果喜欢它返回的对象,在你的榜样重新运行用户,以避免deserilaization在额外开销那些调用它的函数。 – frigon

+0

根据你的评论,我改变了'Get'函数的返回类型为'Task >',然后我可以按照预期得到序列化结果。另外,你可以通过在你的'WebApiConfig.Register()'中添加'config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()'来做一个关于Json序列化的全局配置,你可以按照这个[tutorial](http: //www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#json_camelcasing)以更好地理解它。 –

+0

问题是,通过SDK的序列化到Azure表存储不考虑JsonProperty(“小写”)属性,尽管被串行化以覆盖wire/odata。因此,虽然我可以从MY web api获取数据,并使用尊重属性(小写属性名称),但azure表存储中的数据仍然遵循大写结构。 例如从客户端throught我的web api来通过SDK中的表存储即将进入 PROPERTYNAME(客户端序列化) - >(网络API反序列化)属性名 - >(Azure Table中连载)PROPERTYNAME 只是看起来意外到IMO。 – frigon