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

How to assign two new key values in a JObject from a dictionary?

您好,我调用了以下方法,该方法生成两个字符串值(分区键和行键)。和我的 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 returns 是一个元组,您可以通过 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"
}