如何从字典分配 JObject 中的两个新键值?

问题描述

嗨,我有下面的方法,我调用它并生成两个字符串值(分区键和行键)。而我的 json 没有这两个键,所以我想在我现有的 Json 中添加这两个值。

我需要帮助修改下面的代码以添加这两个键和值:

internal async Task<(string,string)> GenerateKeys( Dictionary<string,EntityProperty> arg )
{            
    var result = await GenerateValuesFromScript( arg,sbForKeyColumns );
    return (result.First().ToString(),result.Last().ToString());
}

var content = JsonConvert.DeserializeObject<JObject>( lines );
   
await GenerateKeys( jsonDictionary );// above method is called and two values are returned
content.Add( new JProperty( "PartitionKey","//this is where I have to pass the above 1st values" ) );
content.Add( new JProperty( "RowKey","//this is where I have to pass the above 2nd values" ) );

解决方法

您需要将 GenerateKeys 的结果赋给一个变量。由于 GenerateKeys 返回一个元组,您可以通过 Item1Item2 简单地引用每个条目 等,语法,将属性添加到您的 JObject。

var lines = "{\"id\": 1}";

var content = JsonConvert.DeserializeObject<JObject>(lines);
var keys = await GenerateKeys();// above method is called and two values are returned
content.Add(new JProperty("PartitionKey",keys.Item1));
content.Add(new JProperty("RowKey",keys.Item2));
    

// This is a very simplistic example of your method since I can't reproduce your params
internal async Task<(string,string)> GenerateKeys()
{
    return await Task.FromResult(("PartitionKeyValue","RowKeyValue"));
}

这会产生以下 JSON:

{
  "id": 1,"PartitionKey": "PartitionKey","RowKey": "RowKey"
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...