Azure Function Cosmos DB输出绑定-自定义JsonSerializerSettings

时间:2019-03-08 04:01:33

标签: azure json.net azure-functions azure-cosmosdb azure-functions-core-tools

我有一个带有CosmosDB输出绑定的Azure函数,如下所示:

public static class ComponentDesignHttpTrigger
{
    [FunctionName("ComponentDesignInserter-Http-From-ComponentDesign")]
    public static IActionResult Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "fromComponentDesign")] HttpRequest request,
        [CosmosDB(
            databaseName: StorageFramework.CosmosDb.DatabaseId,
            collectionName: Storage.ComponentDesignCollectionId,
            ConnectionStringSetting = "CosmosDBConnection")] out ComponentDesign componentDesignToInsert,
        ILogger log)
    {
        var requestBody = new StreamReader(request.Body).ReadToEnd();
        componentDesignToInsert = JsonConvert.DeserializeObject<ComponentDesign>(requestBody);

        return new OkObjectResult(componentDesignToInsert);
    }
}

在此函数中,componentDesignToInsert将自动序列化并在函数完成执行后放入CosmosDB中。但是默认的序列化不会将内容放入camelCase中。为此,Json.NET允许您提供自定义序列化程序设置,如下所示:

var settings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

var json = JsonConvert.SerializeObject(yourObject, settings);

但是我不确定如何将其与输出绑定集成。我该怎么做?

1 个答案:

答案 0 :(得分:1)

当前,输出绑定不会公开序列化程序设置。

您可以做的一件事,就是利用您自己的自定义DocumentClient进行操作。

不过,重要的一点是DocumentClient实例需要是静态的(有关https://github.com/Azure/azure-functions-host/wiki/Managing-Connections的更多详细信息)。

private static Lazy<DocumentClient> lazyClient = new Lazy<DocumentClient>(InitializeDocumentClient);
private static DocumentClient documentClient => lazyClient.Value;

private static DocumentClient InitializeDocumentClient()
{
    // Perform any initialization here
    var uri = new Uri("example");
    var authKey = "authKey";

    var settings = new JsonSerializerSettings
    {
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    };
    return new DocumentClient(uri, authKey, settings);
}

[FunctionName("ComponentDesignInserter-Http-From-ComponentDesign")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "fromComponentDesign")] HttpRequest request,
    ILogger log)
{
    var requestBody = new StreamReader(request.Body).ReadToEnd();
    var componentDesignToInsert = JsonConvert.DeserializeObject<ComponentDesign>(requestBody);

    var collectionUri = UriFactory.GetDocumentCollectionUri(StorageFramework.CosmosDb.DatabaseId, Storage.ComponentDesignCollectionId);
    await documentClient.UpsertDocumentAsync(collectionUri, componentDesignToInsert);
    return new OkObjectResult(componentDesignToInsert);
}

如果适合您的情况,另一种选择是用JsonProperty装饰类。