[英]How to store json content to CosmosDB with CreateDocumentAsync
目标:创建控制台应用程序,其中 1) 从 Azure Data Lake Store 读取 json 2) 将数据存储到 Cosmos DB 中作为 json。(在下一步中,我将在存储之前解析代码中的 json 内容)
问题:在 CosmosDB 中创建了新文档,但它包含某种元数据而不是实际的 json 文件内容。 字符串 json 确实包含我需要的内容,但未正确传递给 CreateDocumentAsync。 我将感谢帮助解决问题,也感谢使代码易于处理的提示 json。
错误:没有错误消息,但错误的内容存储到 CosmosDB。
代码:
private async Task CreateDocumentsAsync()
{
string fileName = "/myjson.json";
// Obtain AAD token for ADLS
var creds = new ClientCredential(applicationId, clientSecret);
var clientCreds = ApplicationTokenProvider.LoginSilentAsync(tenantId, creds).GetAwaiter().GetResult();
// Create ADLS client object
AdlsClient client = AdlsClient.CreateClient(adlsAccountFQDN, clientCreds);
String json = "";
//Read file contents
using (var readStream = new StreamReader(client.GetReadStream(fileName)))
{
string line;
while ((line = readStream.ReadLine()) != null)
{
Console.WriteLine("Read file Line: " + line);
json += line;
}
}
//Read file to json
JsonTextReader reader = new JsonTextReader(new StringReader(json));
//Storing json to CosmosDB
Uri collectionUri = UriFactory.CreateDocumentCollectionUri(databaseName, collectionName);
using (DocumentClient DocumentDBclient2 = new DocumentClient(new Uri(endpointUrl), authorizationKey))
{
Document doc = await DocumentDBclient2.CreateDocumentAsync(collectionUri, reader);
}
}
}
JSON SAMPLE(我想存储这个):
[
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
},
{
color: "blue",
value: "#00f"
},
{
color: "cyan",
value: "#0ff"
},
{
color: "magenta",
value: "#f0f"
},
{
color: "yellow",
value: "#ff0"
},
{
color: "black",
value: "#000"
}
]
JSON 存储到 COSMOSDB:
{
"ArrayPool": null,
"LineNumber": 0,
"LinePosition": 0,
"CloseInput": true,
"SupportMultipleContent": false,
"QuoteChar": "\u0000",
"DateTimeZoneHandling": 3,
"DateParseHandling": 1,
"FloatParseHandling": 0,
"DateFormatString": null,
"MaxDepth": null,
"TokenType": 0,
"Value": null,
"ValueType": null,
"Depth": 0,
"Path": "",
"Culture": "(Default)",
"id": "0189f287-b6ae-4e45-95b8-879293d4c8f3",
"_rid": "nDxrAL1JbwYIAAAAAAAAAA==",
"_self": "dbs/nDxrAA==/colls/nDxrAL1JbwY=/docs/nDxrAL1JbwYIAAAAAAAAAA==/",
"_etag": "\"00006cc5-0000-0000-0000-5a633c900000\"",
"_attachments": "attachments/",
"_ts": 1516453008
}
我遇到了同样的问题。 您需要将 JsonProperty 属性放在您的属性上。 像这样的东西
[JsonProperty(PropertyName = "LastUpdatedByName")]
public string LastUpdatedByName { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.