繁体   English   中英

JSON 字符串作为 Cosmonaut (CosmosDb) 的输入

[英]JSON string as input with Cosmonaut (CosmosDb)

CosmosDB 的 .NET SDK 允许 JSON 字符串作为输入,如下所示:

using (var stream = new MemoryStream())
{
    var writer = new StreamWriter(stream);
    writer.Write("{JSON_string_here}");
    writer.Flush();
    stream.Position = 0;

    ResponseMessage response = await this.container.CreateItemStreamAsync(stream, new PartitionKey("{PK_here}"));

    if (!response.IsSuccessStatusCode)
    {
        //Handle and log exception
    }
    else
    {
        //code logic here
    }
};

Cosmonaut 是否也允许 JSON 字符串作为输入以在容器中创建项目?

通过使用Microsoft.Azure.Cosmos package,在容器中创建项目有两种方法:

public abstract Task<ItemResponse<T>> CreateItemAsync<T>(T item, PartitionKey? partitionKey = null, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken));

public abstract Task<ResponseMessage> CreateItemStreamAsync(Stream streamPayload, PartitionKey partitionKey, ItemRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken));

我为您的请求找到了解决方法,您可以利用Newtonsoft.Json package。

这是我用来测试的快速示例:

    class Program
    {
        private static string EndpointUrl = "https://jackdemo.documents.azure.com:443/";
        private static string PrimaryKey = "AWgnKF********odqAkQwA==";
        private static CosmosClient cosmosClient;
        private static Database database;
        private static Container container;
        private static string databaseId = "db";
        private static string containerId = "demo";
        static void Main(string[] args)
        {
            cosmosClient = new CosmosClient(EndpointUrl, PrimaryKey);
            database = cosmosClient.CreateDatabaseIfNotExistsAsync(databaseId).Result;
            container = database.CreateContainerIfNotExistsAsync(containerId, "/key").Result;
            string json = "{\"id\":\"bbb\",\"key\":\"bbb\"}";
            var obj = JsonConvert.DeserializeObject(json);
            container.CreateItemAsync<Object>(obj).Wait();
            cosmosClient.Dispose();
            Console.ReadLine();
        }
    }

结果

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM