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
}
};
宇航员也允许JSON字符串作为输入在容器中创建商品吗?
答案 0 :(得分:0)
使用Microsoft.Azure.Cosmos
包,有两种方法可以在容器中创建项目:
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
软件包。
这是我用来测试的快速样本:
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();
}
}